mardi 19 juin 2018

JavaScript Function to validate checkbox

I'm trying to not allow both checkboxes to be checked at the same time. Here is my vanilla JS. I have the function already validating to return true when one is checked and false when neither are checked. Radio boxes are not an option.

 function valForm()
{
var both = document.getElementById("cEmail1" & "cPhone1");
for (var i = 1; i <= 2; i++)
{
    if (document.getElementById("cEmail1").checked)
    {
        return true;
    }
    else if (document.getElementById("cPhone1").checked)
    {
        return true;
    }
    else if (both.checked)
    {
        return false;
    }
    else
    { return false; }
}
}

here is my html

<form action="http://severien.com/grit/formecho.php" method="post" 
name="contactUsForm" onsubmit="return valForm()">


<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail"  /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone"  /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div> 
</form>
</div>




Aucun commentaire:

Enregistrer un commentaire