简体   繁体   中英

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.

JavaScript比较运算符是===而不是==

To get the value of the selected ctype item of a form with id myForm:

$('input[name=radioName]:checked', '#myForm').val()

Here's an example:

$('#myForm input').on('change', function() {
   alert($('input[name=ctype]:checked', '#myForm').val()); 
});
<form id="myForm">
<input type="radio" name="ctype" value="1" /> 1 <br />
<input type="radio" name="ctype" value="2" /> 2 <br />
<input type="radio" name="ctype" value="3" /> 3 <br />
</form>

 // alert(document.querySelector('input[type="radio"]:checked').outerHTML); if (document.querySelector('input[type="radio"]:checked')==undefined){ alert("Please select a credit card type."); // return false; } 
 <label for="ctype"> Select Card Type:</label> <br> <label for="visa">Visa</label> <input type="radio" name="ctype" id="visa" value="visa" checked="true" ></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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM