ifwa ifwa - 3 months ago 14
HTML Question

validate coice of more than 2 radio buttons in javascript

I'm trying to get some js to work in checking if one of 3 radio buttons is selected in my html form, but I can't seem to get it to work.

Currently, I'm using



<label for="ctype"> Select Card Type:</label>
<br>
<label for="visa">Visa</label>
<input type="radio" name="ctype" id="visa" value="visa" ></input><br>
<label for="mastercard">Master Card</label>
<input type="radio" name="ctype" id="mastercard" value="mastercard"></input><br>
<label for="amex">American Express</label>
<input type="radio" name="ctype" id="amex" value="amex"></input>







if (document.forms[0].visa.checked == true){
}
else if (document.forms[0].mastercard.checked == true){
}
else if (document.forms[0].amex.checked == true){
}
else {
alert("Please select a credit card type.");
return false;
}





I've also tried running it with document.getElementById(visa/mastercard/amex).checked but had no luck there either.

Unfortunately, I cannot just use the html required as it has to be a js validation.

Answer

JavaScript comparison operator is === instead of ==.

Comments