如果多个复选框中有超过4个答案,如何使用Javascript提醒?

时间:2017-11-07 10:01:11

标签: javascript html forms checkbox

如果复选的复选框超过4个,如何使用Javascript显示提醒?

我写了以下代码,但它没有用。

var select1 = select = document.getElementById('edit-checkbox');

select1.onchange = function() {
if ($('#edit-checkbox').length > 4) {
 alert("Please dont choose more than 4 answers for this question!");
}

<div id="edit-checkbox">
    <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
    <label class="whatever" for="r1"></label>
    <input type="checkbox" name="rGroup" value="2" id="r2" />
    <label class="whatever" for="r2"></label>
    <input type="checkbox" name="rGroup" value="3" id="r3" />
    <label class="whatever" for="r3"></label>
</div>

2-问题:是否可以动态禁用其余复选框,以便不需要显示警报?

1 个答案:

答案 0 :(得分:0)

$('#edit-checkbox input:checkbox:checked').length获取核对次数。请查看下面的代码段以供参考。

&#13;
&#13;
var select1 = select = document.getElementById('edit-checkbox');

select1.onchange = function() {
  if ($('#edit-checkbox input:checkbox:checked').length > 4) {
    alert("Please dont choose more than 4 answers for this question!");
    $('#edit-checkbox input:checkbox').removeAttr('checked');
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="edit-checkbox">
  <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
  <label class="whatever" for="r1"></label>
  <input type="checkbox" name="rGroup" value="2" id="r2" />
  <label class="whatever" for="r2"></label>
  <input type="checkbox" name="rGroup" value="3" id="r3" />
  <label class="whatever" for="r3"></label>
  <input type="checkbox" name="rGroup" value="4" id="r4" />
  <label class="whatever" for="r4"></label>
  <input type="checkbox" name="rGroup" value="5" id="r5" />
  <label class="whatever" for="r5"></label>
</div>
&#13;
&#13;
&#13;

更新:对于第二个问题,您可以使用slice()下面的代码段。

&#13;
&#13;
$('#edit-checkbox input:checkbox').slice(4).attr('disabled', 'disabled');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="edit-checkbox">
  <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
  <label class="whatever" for="r1"></label>
  <input type="checkbox" name="rGroup" value="2" id="r2" />
  <label class="whatever" for="r2"></label>
  <input type="checkbox" name="rGroup" value="3" id="r3" />
  <label class="whatever" for="r3"></label>
  <input type="checkbox" name="rGroup" value="4" id="r4" />
  <label class="whatever" for="r4"></label>
  <input type="checkbox" name="rGroup" value="5" id="r5" />
  <label class="whatever" for="r5"></label>
  <input type="checkbox" name="rGroup" value="6" id="r6" />
  <label class="whatever" for="r6"></label>
</div>
&#13;
&#13;
&#13;