简体   繁体   中英

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.

I need to check if a particular checkbox (for example the one with id=choice3 is checked.

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

Thats how you do it without 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! ");
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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