Roundar Roundar - 2 months ago 7
HTML Question

How do i check if a specific Radio button is checked among the other radio buttons using Javascript?

I am trying to make javascript check if a specific Radio button is checked among the other radio buttons.

The validation method for checking if any radio button works perfectly:

This is a snippet the HTML code containing the radio buttons:

<form id = "buy" name = "buy" onsubmit = "return valiform()">

<input type="radio" name="Card_type" value="visa" > Visa </input>
<input type="radio" name="Card_type" value="mastercard" > Mastercard</input>
<input type="radio" name="Card_type" value="paypal" > Paypal </input>
<input type="submit" value="Confirm order">
</form>


This is the snippet of the Javascript code regarding the radio buttons:

<script type = "text/javascript">
function valiform(){
var visa = document.buy.Card_type;
var mastercard = document.buy.Card_type;
var paypal = document.buy.Card_type;
var message = "Error!\n";
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
if(validateRadio (document.buy.Card_type))
{

}
else
{
message+= "Please select card.\n";
}
if(message != "Error!\n"){
alert(message);
return false;
}
}
</script>


So far the code works perfectly, but I want the code to check if specifically the Paypal radio button is selected. I cannot do it without inducing an error. Any ideas how to do it?

Answer

First change the paypal line to:

<label><input id="paypalRadio" type="radio" name="Card_type" value="paypal"> Paypal </label>

This use this code which will return true if a given radio button is checked:

document.getElementById('paypalRadio').checked

or you could do this without changing anything:

$("td[name=Card_type]")[2].prop("checked", true)
Comments