Reputation: 90
I know how to validate a single checkbox, but what if I have multiple checkboxes and I am saving those values into an array in my database? I want the user to either select one or more check boxes, which pops an alert box.
Below is a snipet of the form and the validator I use. The rest of the form validates fine. I use asp to produce multiple check boxes, but stackoverflow isnt letting display it, so just let you know there is more than one box.
HTML:
<input type="checkbox" name="j" value="<%=getcall_1_ary(jt)%>"/>
Javascript:
if (document.addSC.j.checked == false ) {
alert("Select Desired Job Type")
}
Upvotes: 0
Views: 5834
Reputation: 3843
Try this code.
<script>
function validateCheckBoxes()
{
var isValid = false;
//alert("Check if any checkbox is not checked...");
var allRows = document.getElementsByTagName("input");
for (var i=0; i < allRows.length; i++) {
if (allRows[i].type == 'checkbox' && allRows[i].name == '123') {
if (allRows[i].checked == true) {
return true;
}
}
}
return isValid;
}
function submitBtn (){
if (!validateCheckBoxes()){
alert("no check box selected");
}
else
alert("one or more check box selected");
}
</script>
HTML Part:
<form method="get">
<input type="checkbox" name="123" />
<input type="checkbox" name="123" />
<input type="checkbox" name="123" />
<input type="button" value="submit" onClick="JavaScript:submitBtn();"/>
</form>
Check it now.
Upvotes: 1
Reputation: 4399
Well, first of all, DO VALIDATE YOUR INPUT DATA SERVER-SIDE. I read your question and it suggests that you don't, so this is my tip.
In addition, you can get all checked boxes with the name "j".
var checkboxes = document.getElementsByTagName("input");
var jChecks = [];
for (var i = 0; i <= checkboxes.length; i++) {
if (checkboxes[i].name == "j" && checkbox[i].checked) {
jChecks.push( checkboxes[i] );
}
}
if (jChecks.length > 0) {
alert('more then one selected!');
} else {
alert('select some checkboxes!');
}
Upvotes: 0
Reputation: 2499
I suggest that you use JQuery to query the checkboxes then loop on them to ensure that at least one is checked.
Upvotes: 0