限制可选DOM复选框

时间:2014-12-15 18:25:59

标签: javascript jquery dom checkbox

我试图限制用户可以选择的复选框数量。这些复选框是为数组中的每个项生成的DOM输入对象。我目前没有运气,所以任何帮助都非常感谢。谢谢!

在这里小提琴:http://jsfiddle.net/vVxM2/222/

names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
var numberOf = names.length; 
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
    text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
    }
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;


var limit = 3;
$('input.playerCheckbox').on('change', function(event) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});

3 个答案:

答案 0 :(得分:4)

您的问题出在change事件中。

而不是:

if($(this).siblings(':checked').length >= limit)

你应该这样做:

if($('.playerCheckbox:checked').length >= limit)

此外,如果您的限额最多检查3次,那么您应该:

$('.playerCheckbox:checked').length > limit

因为当引发事件change时,已经检查了当前复选框。

答案 1 :(得分:2)

您的问题在此处找到:if($(this).parent().siblings().children(":checkbox:checked").length >= limit)。您实际上有两个父母,因此您应该添加另一个parent()children()功能。它应该看起来像if($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit)

&#13;
&#13;
names = ["Donny", "Danny", "Ricky", "Eric", "Jamie", "Bobby", "Booby"];
var numberOf = names.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
  text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
}
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;


var limit = 3;
$('input.playerCheckbox').on('change', function() {
  if ($(this).parent().parent().siblings().children().children(":checkbox:checked").length >= limit) {
    $(this).attr('checked', false);
    alert('You can only select 3 checkboxes.');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recentPlayersContainer">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

DEMO

 names =["Donny","Danny","Ricky","Eric","Jamie","Bobby","Booby"];
        var numberOf = names.length; 
        var text = "<ul>";
        for (i = 0; i < numberOf; i++) {
            text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
            }
        text += "</ul>";
        document.getElementById("recentPlayersContainer").innerHTML = text;


    var limit = 3;
    $('input.playerCheckbox').on('change', function(event) {
            if($('input.playerCheckbox:checked').length >= limit + 1) {
              alert('enough');
            }
    });