[英]How can I know if the checkbox is checked when all the fields have unique id?
To know if the checkbox has been checked or not, I have been calling this function. 要知道该复选框是否已选中,我一直在调用此函数。 (when the user click submit button) delete_checkbox
is the id
of the checkbox field that is being checked. (当用户单击提交按钮时) delete_checkbox
是正在检查的复选框字段的id
。
function ifChecked() {
if(!document.getElementById("delete_checkbox").checked)
alert("Select the tweet!");
}
How can I check when the id
of the checkbox is generated dynamically ? 如何检查复选框id
是何时动态生成的? For example : 例如 :
<input type="checkbox" id="1" />
<input type="checkbox" id="78" />
For the above 2 fields, how can the above function be modified when the user clicks the submit
button ? 对于以上两个字段,当用户单击“ submit
按钮时,如何修改以上功能?
Give each of the checkboxes the same name
. 为每个复选框指定相同的name
。 The <form>
tag as a property called elements
which gives you access to all the fields within the form. <form>
标记作为称为elements
的属性,使您可以访问表单中的所有字段。
<form ... onsubmit="foo(event, this);">
<input type="checkbox" name="delete_me" id="1">
<input type="checkbox" name="delete_me" id="2">
<input type="checkbox" name="delete_me" id="3">
<button type="submit">Submit</button>
</form>
Then some JavaScript: 然后是一些JavaScript:
function foo(event, form) {
event.preventDefault(); // keep form from submitting
var deleteCheckboxes = form.elements.delete_me;
for (var i = 0; i < deleteCheckboxes.length; i++) {
if (deleteCheckboxes[i].checked) {
console.log(deleteCheckboxes[i].id + " is checked");
}
}
}
If you want to know if there are any unchecked checkboxes: 如果您想知道是否有任何未选中的复选框:
if (document.querySelectorAll("input[type=checkbox]:not(:checked)").length > 0) {
alert("Please select all the tweets!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.