Javascript : Multiple Checkbox Validation
I am trying to work out this code, but this thing is not working!
Javascript:
if(form.interest[0].checked==false && form.interest[1].checked==false && form.interest[2].checked==false && form.interest[3].checked==false)
{
alert("Please Check");
return false;
}
HTML:
<input type="checkbox" name="interest[]" value="News"/>News
<input type="checkbox" name="interest[]" value="Health"/>Health
<input type="checkbox" name="interest[]" value="Automobiles"/>Automobiles
<input type="checkbox" name="interest[]" value="Internet"/>Internet
Please guide and tell me how to do multiple checkbox validation using javascript.
Answer:
The issue with your code is that in JavaScript, form elements are not accessed with PHP-like array syntax. You should use the document.getElementsByName
method, which returns an array-like object of all child elements which have the given name.
You can then iterate over this array to check if any of the checkboxes are checked.
function validate() {
var checkboxes = document.getElementsByName('interest[]');
var isChecked = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please Check");
return false;
}
return true;
}
And in your HTML form, you'll need to use this function validate()
for submission. You can add it to the onsubmit
attribute of the form. Here is an example:
<form onsubmit="return validate()">
<input type="checkbox" name="interest[]" value="News"/>News
<input type="checkbox" name="interest[]" value="Health"/>Health
<input type="checkbox" name="interest[]" value="Automobiles"/>Automobiles
<input type="checkbox" name="interest[]" value="Internet"/>Internet
<input type="submit" value="Submit">
</form>
I hope this answers your question. Let me know if you have follow-up questions.