我有10个具有以下值的复选框,
7:00
8:00
8:30
9:00
9:30
10:00
10:30
11:00
11:30
12:00
现在只考虑7:00到9:00已经检查过了。当我检查11:30时,我应该获取所有值,应该在9:00到11:30之间进行选择
所以检查11:00后我的结果应该是
7:00
8:00
8:30
9:00
9:30
10:00
10:30
11:00
11:30
12:00
到目前为止我的代码:
HTML代码是
<input type="checkbox" name="timer" id="timer" value="8:00" />
<input type="checkbox" name="timer" id="timer" value="8:30" />
<input type="checkbox" name="timer" id="timer" value="9:00" />
<input type="checkbox" name="timer" id="timer" value="9:30" />
<input type="checkbox" name="timer" id="timer" value="10:00" />
<input type="checkbox" name="timer" id="timer" value="10:30" />
<input type="checkbox" name="timer" id="timer" value="11:00" />
<input type="checkbox" name="timer" id="timer" value="11:30" />
<input type="checkbox" name="timer" id="timer" value="12:00" />
<input type="checkbox" name="timer" id="timer" value="12:30" />
jQuery代码是
var chkdtime = $('input[name="timecheckbox"]:checked').map(
function()
{
return this.value;
}
).get();
var a=chkdtime.shift();
var b=chkdtime.pop();
最佳答案
我认为这段代码可以满足您的需求:
var $checks = $(':checkbox[name=timer]').on('change', function() {
var $checked = $checks.filter(':checked'),
changedIndex = $checks.index(this),
$start = $checked.eq(0),
$end = $checked.eq($checked.length - 1),
from = $checks.index($start),
to = $checks.index($end);
if (changedIndex < to) {
$checks.slice(changedIndex).prop('checked', false);
to = changedIndex;
}
$checks.slice(from, to).prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="timer" id="timer" value="8:00" checked /> 8:00 <br>
<input type="checkbox" name="timer" id="timer" value="8:30" checked /> 8:30 <br>
<input type="checkbox" name="timer" id="timer" value="9:00" checked /> 9:00 <br>
<input type="checkbox" name="timer" id="timer" value="9:30" checked /> 9:30 <br>
<input type="checkbox" name="timer" id="timer" value="10:00" /> 10:00 <br>
<input type="checkbox" name="timer" id="timer" value="10:30" /> 10:30 <br>
<input type="checkbox" name="timer" id="timer" value="11:00" /> 11:00 <br>
<input type="checkbox" name="timer" id="timer" value="11:30" /> 11:30 <br>
<input type="checkbox" name="timer" id="timer" value="12:00" /> 12:00 <br>
<input type="checkbox" name="timer" id="timer" value="12:30" /> 12:30 <br>
关键思想是使用
index()
方法计算选中复选框的索引,然后检查/取消选中两者之间的值。