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:
News
Health
Automobiles
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:
I hope this answers your question. Let me know if you have follow-up questions.
Replies
-
Kaustubh KatdareI'd strongly using jQuery unless you've special interest in learning plain vanilla JS. That said, you should always look at the 'Console' in Chrome by inspecting your page.
I'm not well versed with JavaScript; but here's a working example of your code.
CheckBox Validation -
Anoop KumarIf you really want to go with only javascript to build the foundation of scripting. Here is the code.
HTML in Body tag
Javascript code inside Head tag
Problems:
- You are not using document (primary node) to find the elements in page.
- How does javascript will be called. You need call piece of script (say a function) to execute on an event. Such as checking and unckecking of a checkbox.
You are reading an archived discussion.