我有一堆复选框,我想限制用户根据选择框值检查复选框。
例如,如果用户在选择框中选择值-3,那么他只能选中3-复选框(任意三个)。
演示:小提琴
<select id="count">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select><br/><br/>
<div class="checkbox">
<input id="checkbox-1" type="checkbox" name="Data1" value="option1" />
<label for="checkbox-1">HTML</label>
<br />
<input id="checkbox-2" type="checkbox" name="Data2" value="option2" />
<label for="checkbox-2">CSS</label>
<br />
<input id="checkbox-3" type="checkbox" name="Data3" value="option3" />
<label for="checkbox-3">HTML</label>
<br />
<input id="checkbox-4" type="checkbox" name="Data4" value="option4" />
<label for="checkbox-5">CSS</label>
<br />
<input id="checkbox-5" type="checkbox" name="Data5" value="option5" />
<label for="checkbox-5">HTML</label>
<br />
<input id="checkbox-6" type="checkbox" name="Data6" value="option6" />
<label for="checkbox-6">CSS</label>
</div>我该怎么做?有人能帮帮我吗?
发布于 2013-09-09 14:03:10
如果您的意思是选项val =3 ->可以选中3个复选框,那么尝试下面的http://jsfiddle.net/HNmhL/9/
Javascript
$(document).ready(function(){
$('#count').on('change', function(){
$('input[type=checkbox]').prop('checked', false);
});
$('input[type=checkbox]').on('change', function(){
if($('input[type=checkbox]:checked').length > $('#count').val()){
$(this).prop('checked', false);
}
});
});发布于 2013-09-09 14:07:11
根据Pavlo的有益评论更新
演示: http://jsfiddle.net/HNmhL/23/
JQuery
// Cache the selector
var checkBoxes = $('input[type=checkbox]');
checkBoxes.click(function() {
validateCheckboxes();
});
$('#count').change(function() {
// Only neave the first N items checked (where N = number of items allowed)
checkBoxes.filter(':checked:gt(' + ($(this).val() - 1) + ')').attr('checked', false);
validateCheckboxes();
});
function validateCheckboxes() {
// If the number of checked items exceeds the number allowed
if (checkBoxes.filter(':checked').length >= $('#count').val()) {
// Disable all un-checked boxes...
checkBoxes.not(':checked').attr('disabled', true);
} else {
// We haven't hit out limit yet; make sure the checkboxes are still enabled
checkBoxes.attr('disabled', false);
}
};发布于 2013-09-09 14:04:29
使用这个
$('input[id^="checkbox-"]').hide();
$('select').on('change', function (e) {
var valueSelected = this.value;
for(i=1;i<=valueSelected;i++)
{
$('#checkbox-' + i).show();
}
});https://stackoverflow.com/questions/18699839
复制相似问题