我希望每次用户使用Jquery或javascript单击某个复选框时,都能动态地将所有选中的复选框放入一个数组中。PS:我使用Django + Python来生成选项,Bootstrap来设置它们的样式,下面是我的代码:
{% for option in options %}
<div class="input-group" style="margin-bottom: 7px;">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" name="checks[]" aria-label="Radio button for following text input" id="option_choice" class="ipad_pro" value="{{ option.name }}" onclick="getCheckedCheckboxes('option_choice')">
</div>
</div>
<input style="background-color: #fff;" type="text" class="form-control" disabled=True value="{{ option.name }} {{ option.price }}€" aria-label="Text input with radio button">
</div>
{% endfor %}
到目前为止,我尝试这样做:
function getCheckedBoxes(chkboxId) {
var checkboxes = document.querySelectorAll('#' + chkboxId);
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
var checkedBoxes = getCheckedBoxes("option_choice");
但这对我来说并不管用。
如果你知道我的问题的答案,请帮助我。
发布于 2018-07-28 06:02:37
发布于 2018-08-08 01:41:59
要使用JS获取所有选中的复选框输入,请执行以下操作:
var checked = document.querySelectorAll("input[type=checkbox]:checked");
发布于 2018-07-28 06:22:26
<input type="checkbox" name="checks[]" aria-label="Radio button for following text input" id="option_choice" class="ipad_pro" value="{{ option.name }}"
onclick="getCheckedCheckboxes('option_choice')">
您正试图在getCheckedCheckboxes
方法上绑定一个单击处理程序,但您的函数名是getCheckedBoxes
,因此单击该元素不会运行该方法。
https://stackoverflow.com/questions/51566003
复制相似问题