Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  122] [ 7]  / answers: 1 / hits: 130162  / 12 Years ago, fri, august 3, 2012, 12:00:00

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.




JS (wrong)




function valthis(){
if (document.FC.c1.checked) {
alert (thank you for checking a checkbox)
} else {
alert (please check a checkbox)
}
}



HTML




<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = FC>
<input type = checkbox name = c1 value = c1/> C1
<br>
<input type = checkbox name = c1 value = c2/> C2
<br>
<input type = checkbox name = c1 value = c3/> C3
<br>
<input type = checkbox name = c1 value = c4/> C4
<br>
</form>
<br>
<br>

<input type = button value = Edit and Report onClick = valthisform();>



So what I ended up doing in JS was this:




function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked

if (chkd == true){

} else {
alert (please check a checkbox)
}

}


I decided to drop the Thank you part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.


More From » html

 Answers
38

You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?



Here's a non-jQuery solution to check if any checkboxes on the page are checked.



var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);


You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.


[#83885] Wednesday, August 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;