Javascript Checkbox Form Validation
I'm trying to use this link as my resource: http://www.w3schools.com/js/js_form_validation.asp I understand how it works for textboxes, but how do you make it detect form validatio
Solution 1:
Here is an example that does what you are asking and can be tested within this page:
functionValidate(){
if(!validateForm()){
alert("You must check atleast one of the checkboxes");
returnfalse;
}
returntrue
}
functionvalidateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){returntrue}
}
}
returnfalse;
}
<formname="myForm"action="demo_form.asp"onsubmit="return Validate()"method="post">
Option 1: <inputtype="checkbox"name="option1"value="1"><br />
Option 2: <inputtype="checkbox"name="option2"value="2"><br /><inputtype="submit"value="Submit Form"></form>
Solution 2:
functionValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
returnfalse;
}
if (ErrorText= "") { form.submit() }
}
<formname="feedback"action="#"method=post>
Your Gender: <inputtype="checkbox"name="gender"value="Male"> Male
<inputtype="checkbox"name="gender"value="Female"> Female
<inputtype="reset"value="Reset"><inputtype="button"name="SubmitButton"value="Submit"onClick="ValidateForm(this.form)"></form>
Post a Comment for "Javascript Checkbox Form Validation"