div中的jquery限制复选框

问题描述 投票:0回答:3

我想限制表单中可用复选框的数量。我尝试使用以下jquery代码

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

这很有效。但是如果输入标记在div标记内,则jquery停止工作。

例:

<div class='voteContainer'>
    <input name='vote1' value='1' class='checkbox' type='checkbox' />
</div>
<div class='voteContainer'>
    <input name='vote2' value='3' class='checkbox' type='checkbox' />
</div>
<div class='voteContainer'>
    <input name='vote3' value='3' class='checkbox' type='checkbox' />
</div>

我如何更改jquery以在div中使用此输入标记?

提前谢谢了

jquery html forms checkbox input
3个回答
0
投票

为什么不将它包装在父div中并计算所有被检查的复选框?

var limit = 2;
$('input.checkbox').on('change', function(evt) {
    if($('#checkboxes input.checkbox:checked').length > limit) {
       this.checked = false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div id="checkboxes">
<div class='voteContainer'>
    <input name='vote1' value='1' class='checkbox' type='checkbox' />
</div>
<div class='voteContainer'>
    <input name='vote2' value='3' class='checkbox' type='checkbox' />
</div>
<div class='voteContainer'>
    <input name='vote3' value='3' class='checkbox' type='checkbox' />
</div>
</div>

1
投票

他们不再是兄弟姐妹了。使用类div统计出现在voteContainer中的那些,如下所示:

var limit = 2;
$('input.checkbox').on('change', function(evt) {
    if($('div.voteContainer input:checked').length >= limit) {
        this.checked = false;
    }
});

1
投票

试试这个:

$("input[name='tech']").change(function () {
      var maxAllowed = 2;
      var cnt = $("input[name='tech']:checked").length;
      if (cnt > maxAllowed)
      {
         $(this).prop("checked", "");
         alert('Select maximum ' + maxAllowed + ' technologies!');
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="tech" value="jQuery" /> jQuery <br/>

<input type="checkbox" name="tech" value="JavaScript" />JavaScript <br/>

<input type="checkbox" name="tech" value="Prototype" /> Prototype<br/>

<input type="checkbox" name="tech" value="Dojo" /> Dojo<br/>

<input type="checkbox" name="tech" value="Mootools" /> Mootools <br/>
© www.soinside.com 2019 - 2024. All rights reserved.