javascript at least 1 checkbox checked before form submit

Hey folks,

I have a fairly simple setup, a form with 3 checkboxes and a submit button, and I'm trying to ensure the user checks at least 1 of the checkboxes before submitting the form, but I seem to be doing something incorrectly. It doesn't produce an error, but it doesn't appear to do anything else either.

Here's what I'm using:

JAVASCRIPT:
-----------------
function validate_checkbox() {

var ckbx_arr=document.getElementsByName('item_select');

var ckbx_arr_ln=ckbx_arr.length;
for(var i=0;i<ckbx_arr_ln;i++){
if(ckbx_arr[i].checked)return true;
}
return false;

}
---------------------

HTML:
---------------------
            <form action="processform.php" method="post" name="ChooseItems">
                  3:<input type="checkbox" name="item_select" value="3">
                  2:<input type="checkbox" name="item_select" value="2">
                  1:<input type="checkbox" name="item_select" value="1">

            <input name="Submit" type="submit" value="submit" onClick="validate_checkbox()" />
            </form>



Where I'm going wrong at?

Thanks!

jmoriartyAsked:
Who is Participating?
 
StealthyDevCommented:
you should give

onClick="return validate_checkbox()"

return keyword is missing
0
 
StealthyDevCommented:
If required you can alert the user to select atleast one check-box like this:


function validate_checkbox() {

var ckbx_arr=document.getElementsByName('item_select');

var ckbx_arr_ln=ckbx_arr.length;
for(var i=0;i<ckbx_arr_ln;i++){
if(ckbx_arr[i].checked)return true;
}
alert("please select atleast one option!");
return false;

}

Open in new window

0
 
RobinSoftware EngineerCommented:
Can you try changing the onClick event from

onClick="validate_checkbox()"

to

onClick="return validate_checkbox()"
0
 
jmoriartyAuthor Commented:
duh, always something simple you overlook, thanks guys.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.