3

我有一堆复选框,我想限制用户根据选择框值检查复选框。

例如,如果用户在选择框中选择值 - 3,那么他只能选中 3-checkboxes(任意三个)

演示:小提琴

HTML

<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>

我怎样才能做到这一点?请问有人可以帮我吗?

4

4 回答 4

3

根据 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-09T14:07:11.560 回答
2

如果你的意思是选项 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-09T14:03:10.427 回答
0

用这个

$('input[id^="checkbox-"]').hide();

$('select').on('change', function (e) {
    var valueSelected = this.value;
    for(i=1;i<=valueSelected;i++)
    {
        $('#checkbox-' + i).show();
    }
});
于 2013-09-09T14:04:29.360 回答
0

这可以用非常少的代码在单个条件检查中完成:

$('input[type=checkbox]').on('click', function(event){
    if($('div.checkbox input[type=checkbox]:checked').length > $('#count').val())
    {
        event.preventDefault();
    }
});

看看这个小提琴例子。

于 2013-09-09T14:11:20.893 回答