如果复选的复选框超过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-问题:是否可以动态禁用其余复选框,以便不需要显示警报?
答案 0 :(得分:0)
按$('#edit-checkbox input:checkbox:checked').length
获取核对次数。请查看下面的代码段以供参考。
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;
更新:对于第二个问题,您可以使用slice()
下面的代码段。
$('#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;