【发布时间】:2015-08-14 23:47:49
【问题描述】:
好的,所以我有一些 javascript 代码旨在做两件事:勾选具有相同值的复选框(如果选中值为“3”的复选框,则还应选中任何其他值为“3”的复选框)。这也意味着计算之后总共有多少个复选框。这完美无缺。
$(".chkbox").on('change',function() {
var max_number =8;
var val = ($(this).val();
if ($(this).is(":checked")) {
$(":checkbox[value='" + val + "']").prop("checked", true);
} else {
$(":checkbox[value='" + val + "']").prop("checked", false);
}
var count = $("[type='checkbox']:checked").length;
if (count>=max_number){
alert("too many chosen!");
}
alert (count);
});
但是,html 中有一些不相关的复选框,并且被错误地计数。因此,我为包含相关复选框的部分提供了“test”的 id 并重写了 javascript:
$(".chkbox").on('change', function() {
var max_number = 8;
var val = ($(this).children("#test")).val();
if (($(this).children("#test")).is(":checked")) {
$(":checkbox[value='" + val + "']").prop("checked", true);
} else {
$(":checkbox[value='" + val + "']").prop("checked", false);
}
var count = $("[type='checkbox']:checked").length;
if (count >= max_number) {
alert("too many chosen!");
}
alert(count);
});
<section id="test">
<table style="display:inline-block;" border="1">
<tr id="9">
<td>9</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
</td>
</tr>
<tr id="10">
<td>10</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
</td>
</tr>
<tr id="11">
<td>11</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
</td>
<td> </td>
</tr>
<tr id="12">
<td>12</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
</td>
<td> </td>
</tr>
<td>18</td>
<td style="background-color:#">
<input type="checkbox" class="chkbox" name="selection[array_name][]" title="2" value="2" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
</td>
<td> </td>
</tr>
</table>
</section>
这会正确计算复选框的数量 - 但它不再勾选测试中具有相同值的所有复选框!我该如何解决这个问题?
【问题讨论】:
-
你也可以分享你的 HTML 吗?
-
@VimalanJayaGanesh 完成...我不得不减少它(实际上是几百行),但应该准确反映整体代码
标签: javascript jquery checkbox