JavaScript:根据唯一CLASS限制已检查允许框的数量

时间:2013-10-15 07:08:27

标签: javascript jquery

我有这个Java脚本代码

var maxCheckedCount = 3;
var CLASS = 'Woops! Too many selected!';

    jQuery('input[type=checkbox]').click(function(){
        var n = jQuery('input:checked').length;
        if(n>=maxCheckedCount){
            jQuery(this).prop('checked',false);
            alert(maxCheckedAlertMessage);
        }
    });

然后是HTML复选框列表。

<input type="checkbox">1
<br>
<input type="checkbox">2
<br>
<input type="checkbox">3
<br>
<input type="checkbox">4
<br>
<input type="checkbox">5
<br>


<ul   CLASS="options-34-list">
<li>
<input type="checkbox">6
</li>
<input type="checkbox">7
<li>
<input type="checkbox">8
</li>
<li>
<input type="checkbox">9
</li>
<li>
<input type="checkbox">10
</li>
</ul>

我如何才能根据复选框的CLASS CLASS =“options-34-list”来应用限制允许的框数的JavaScript,而不是所有列表。

3 个答案:

答案 0 :(得分:3)

这是我的版本!

$.fn.maxSelectedCheckboxes = maxSelectedCheckboxes;

function maxSelectedCheckboxes(maxSelected) {
    var $targets = this;
    $targets.on('click', function() {
        var $checked = $targets.filter(':checked');
        if ($checked.length > maxSelected) {
            $checked.not(this).first().removeAttr('checked');
        }
    });
};

小提琴:http://jsfiddle.net/S8ZTA/

这很好,因为它可以用于复制框集合中应用的任何选择器:

$('#options-34-list input[type="checkbox"]').maxSelectedCheckboxes(3);

答案 1 :(得分:1)

使用.find()搜索给定节点后代内的节点。

在列表#options-34-list中找到的已检查项目数:

$('#options-34-list').find('input:checked').length

答案 2 :(得分:1)

id属性必须是唯一的,您可以改用类。

HTML:

<input type="checkbox">1
<br>
<input type="checkbox">2
<br>
<input type="checkbox">3
<br>
<input type="checkbox">4
<br>
<input type="checkbox">5
<br>
<input type="checkbox" class="options-34-list">6
<br>
<input type="checkbox" class="options-34-list">7
<br>
<input type="checkbox" class="options-34-list">8
<br>
<input type="checkbox" class="options-34-list">9
<br>
<input type="checkbox" class="options-34-list">10
<br>

JS:

jQuery('input[type=checkbox]').click(function () {
    var n = jQuery('.options-34-list:checked').length;
    if (n > maxCheckedCount) {
        jQuery(this).prop('checked', false);
        alert(maxCheckedAlertMessage);
    }
});

演示:http://jsfiddle.net/IrvinDominin/ATbvM/