Skip to content Skip to sidebar Skip to footer

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:

function Validate(){
   if(!validateForm()){
       alert("You must check atleast one of the checkboxes");
       return false;
   }
return true
}
function validateForm()
{
    var c=document.getElementsByTagName('input');
    for (var i = 0; i<c.length; i++){
        if (c[i].type=='checkbox')
        {
            if (c[i].checked){return true}
        }
    }
    return false;
}
<form name="myForm" action="demo_form.asp" onsubmit="return Validate()" method="post">
Option 1: <input type="checkbox" name="option1" value="1"><br />
Option 2: <input type="checkbox" name="option2" value="2"><br />
<input type="submit" value="Submit Form">
</form>

Solution 2:

function ValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if (ErrorText= "") { form.submit() }
}
<form name="feedback" action="#" method=post>
Your Gender: <input type="checkbox" name="gender" value="Male"> Male
<input type="checkbox" name="gender" value="Female"> Female

<input type="reset" value="Reset">
  <input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
</form>

Post a Comment for "Javascript Checkbox Form Validation"