【发布时间】:2021-04-19 05:29:47
【问题描述】:
我有 5 个 html 复选框,但每次它们具有不同的值时,我希望每次选中或取消选中复选框时调用此 js 函数以获取所有选中的复选框并将其添加到隐藏输入中
这是我的html
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="1" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="2" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="3" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="4" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="5" onchange="getValue(this.value)">
<input type="hidden" id="ticketsPay" name="ticketsPay" value="">
这是我的 js
let myArray = (function() {
let a = [];
$(".checkboxes:checked").each(function() {
a.push(this.value);
});
return a;
})()
document.getElementById('ticketsPay').value = myArray.toString();
JS不要在隐藏输入中保存所有选中的复选框有什么想法吗?
【问题讨论】:
-
(Offtopic):不要使用内联 JS
on*处理程序,就像你不使用内联style属性一样。 CSS 和 JS 应该只在一个地方,那就是它们各自的文件或标签。 -
回归基础:ID 应该是唯一的!
-
您正在查询
.checkboxes,而您的复选框属于.checkbox。不要将语法与代码混淆!
标签: javascript html checkbox