简体   繁体   English

检查复选框列表中的特定复选框是否已选中

[英]Checking if a particular checkbox in a checkbox list is checked

I have a list of checkboxes: 我有一个复选框列表:

<input name="choice" type="checkbox" id="choice1" value="A" /> 
<input name="choice" type="checkbox" id="choice2" value="B" />
<input name="choice" type="checkbox" id="choice3" value="C" />
<input name="choice" type="checkbox" id="choice4" value="D" />

Name is the same for all but id is different. 所有人的名称相同,但id不同。

I need to check if a particular checkbox (for example the one with id=choice3 is checked. 我需要检查一个特定的复选框(例如,是否选中了id = choice3的复选框。

Tried 试过了

if (this.choice.id === "choice3" && this.choice[2].checked) {
    alert("checked!");      
}

but it does not work - the alert is never reached 但它不起作用-永远不会达到警报

PS I need to use javascript not jquery PS我需要使用JavaScript而不是jQuery

Thats how you do it without jQuery: 那就是没有jQuery的情况:

Suppose your form is like this: 假设您的表单是这样的:

<form id="myForm" action="test.php">
    <input name="choice" type="checkbox" id="choice1" value="A"/>
    <input name="choice" type="checkbox" id="choice2" value="B"/>
    <input name="choice" type="checkbox" id="choice3" value="C"/>
    <input name="choice" type="checkbox" id="choice4" value="D"/>
    <input type="button" onclick="validate();" value="Submit form">
</form>

You can do the validation on submit this way: 您可以通过以下方式对提交进行验证:

function validate() {

if (document.getElementById('choice3').checked) {
    alert("checked");
} else {
    alert("You didn't check it! ");
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM