简体   繁体   English

当所有字段都具有唯一ID时,如何知道该复选框是否已选中?

[英]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.

相关问题 如何清除所有复选框当选中复选框id =“ checkAll”时? - How to clear all checkbox When checkbox id=“checkAll” are checked? 当我有一个空数组作为我的 check.bind 时,如何创建一个 select 全部复选框 - How do I create a select all checkbox when I have an empty array as my checked.bind 你怎么能告诉 reactJs 每个复选框都是唯一的,所以当我更改一个框的 checked 属性时,它不会勾选所有其他框? - How can you tell reactJs that each checkbox is unique so when I change the checked attribute for one box it doesn't tick all the other boxes? 选中另一个复选框后,如何检查该复选框? [JavaScript的] - How can I check a checkbox when another checkbox is checked? [JavaScript] 当我选中所有复选框时如何选择所有复选框 - How to select all checkbox when i checked all check boxes 选中初始复选框时(如何使用PHP / Javascript)如何显示多个复选框 - How can I have multiple checkboxes appear when initial checkbox is checked (using PHP/Javascript) 如何知道是否选中了一个复选框 - How to know if a checkbox is checked 如何知道是否选中了复选框? - How to know if a checkbox is checked? 如何知道是否选中了复选框? - How to know if checkbox is checked? 选中复选框时如何使用 id 显示和隐藏 - How to Show and Hide with id when the checkbox is checked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM