Checkbox Validation

Associate
Joined
18 Oct 2002
Posts
1,725
Location
Belfast
I have a checkbox at the end of a form which needs validated. No other section on the form apart from this 'one' checkbox needs any validation or coding.

Could anyone give me a simple bit of JS that would do this? Anything I have seen seems very confusing or for multiple boxes etc...

It simply needs to give a message that the box needs to be ticked to agree to terms and conditions.

Any help would be great :)
 
Code:
<html>
<head>
<script language="JavaScript">
<!--
function validate_form ()
{
    valid = document.myform.terms.checked;
    if (!valid)    
    {
        alert("Agree to terms!");
    }
    return valid;
}
//-->
</script>
</head>
<body>
<form name="myform" method="post" action="submitme.php" onSubmit="return validate_form();">
<input type="checkbox" name="terms">
<br>
<input type="submit" name="submitbtn" value="Submit">
</form>
</body>
</html>

Basically add, onSubmit to the FORM tag and it will only submit if the value is true,
It then calls validate_form(), which only returns the boolean value for whether the box is checked or not. If it is false a message is displayed.
 
Put this in the head tags of your webpage.
Code:
<script language="JavaScript">
<!--
function validate_form ()
{
    valid = document.myform.terms.checked;
    if (!valid)    
    {
        alert("Agree to terms!");
    }
    return valid;
}
//-->
</script>

add this to the form tag you have (the form that contains the checkbox)
Code:
 onSubmit="return validate_form();"

Code:
"Agree to terms!"
is the message that appears when they dont check the box
Code:
document.myform.terms.checked
here you need to change "myform" to the name of your form, if it doesnt have one add
Code:
name="form_name_here"
to the form tag (where you put the onSubmit code)
Then change "terms" to the name of the checkbox, again if you haven't specified one give it a name in similar fashion to the form
For the names see my code if you are in doubt

Ric.
 
Back
Top Bottom