1

我有这个 JavaScript 代码

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 应用于所有列表。

4

3 回答 3

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);
于 2013-10-15T07:17:45.297 回答
1

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

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

$('#options-34-list').find('input:checked').length
于 2013-10-15T07:14:32.183 回答
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/

于 2013-10-15T07:15:07.840 回答