简体   繁体   English

JavaScript:根据唯一的CLASS限制选中的允许框的数量

[英]JavaScript: Limit number of checked allowed boxes based on unique CLASS

I have this Java-Script code 我有这个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);
        }
    });

and then here is HTML check-boxes list. 然后是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>

How can i only apply the JavaScript of limiting the allowed number of boxes based on the CLASS CLASS="options-34-list" of the checkbox not to all list. 我如何仅将基于复选框的CLASS CLASS =“ options-34-list”限制允许的框数的JavaScript不适用于所有列表。

Here's my version! 这是我的版本!

$.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');
        }
    });
};

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

It's nice because it can be used on any selector applied across a collection of checkboxes: 很好,因为它可以用于跨复选框集合应用的任何选择器:

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

Use .find() to search for nodes inside the descendants of a given node. 使用.find()在给定节点的后代中搜索节点。

Number of checked items found inside the list #options-34-list : 在列表#options-34-list找到的已检查项目数:

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

The id attribute must be unique, you can use a class instead. id属性必须唯一,您可以使用类。

HTML: 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: 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);
    }
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM