Forum Moderators: open

Message Too Old, No Replies

form validation

get users to check box before submitting

         

HelenDev

3:34 pm on Feb 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is kind of a continuation of a question I asked a while back. It has taken me so long to get around to doing this that the thread has expired!

Anyway...

Fotiman very kindly posted some code to do this...


<script type="text/javascript">
function isChecked( checkboxId )
{
var cbox = document.getElementById(checkboxId);
if(!cbox ) return false;
if( cbox.checked )
{
return true;
}
return false;
}
</script>
<form onsubmit="return isChecked(myCheckBox)">
<input type="checkbox" id="myCheckBox" name="myCheckBox">
<input type="submit" name="submit" value="Submit">
</form>

But my knowledge of javascript is a bit basic, so how do I use the returned value of the function to create an alert?

Also, including the onsubmit part seems to stop my form from actually submitting?

Bernard Marx

4:26 pm on Feb 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is a basic version. I removed the bit that checks for the existence of the checkbox itself. We might as well assume it exists (although we could check for DOM 1 support, and return true if not).

<script type="text/javascript"> 
function isChecked( checkboxId )
{
var cbox = document.getElementById(checkboxId);
var valid = cbox.checked; /* boolean value */
if(!valid)
alert("Oi! That box ain't checked");
return valid;
}
</script>
<form onsubmit="return isChecked(myCheckBox)">
<input type="checkbox" id="myCheckBox" name="myCheckBox">
<input type="submit" name="submit" value="Submit">
</form>