I'm having problem with getting radio button value. I search thru and follow instruction of the same issues in stackoverflow but doesn't help. I'd appreciate it if you can help:
The radio_value in the code below always return null.
<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>Template</TITLE> <script> function payment_validation(){ var radio_value=""; var radios=document.getElementsByName("payment"); for (var i=0;i<radios.length;i++){ if(radios[i].checked){ radio_value=radios[i].value; return radio_value; break; } } if(radio_value!=""){ document.getElementById("payment_error").innerHTML=""; return true; } else{ document.getElementById("payment_error").innerHTML="Please select radio"; return false; } } </script> </HEAD> <BODY> <p> Payment Options: <input type="radio" name="payment" id="CC" value="">CreditCard <input type="radio" name="payment" id="DC" value="">DebitCard <input type="radio" name="payment" id="PP" value="">Paypal <span style=color:red id= payment_error></span> </p> <p> <input type="button" id="submit_id" value=" SUBMIT " onclick="payment_validation()"> </p> </BODY> </HTML>
use .checked instead of .value. That should help and make it not NULL. so itv would be
radio_value=radios[i].checked;
A few things:
payment_validation
function to return true or false; so remove the line return radio_value
, and instead just break
. var
more than once. <p>
tag. payment_error
id, so the code generates an error as is. <span>
tag is malformed; it is missing quotes around the attribute values and has a space before payment_error
. Altogether, now:
HTML:
<p>
Payment Options:
<input type="radio" name="payment" id="CC" value="CreditCard">CreditCard
<input type="radio" name="payment" id="DC" value="DebitCard">DebitCard
<input type="radio" name="payment" id="PP" value="Paypal">Paypal
</p>
<p>
<input type="button" id="submit_id" value=" SUBMIT " onclick="payment_validation()">
</p>
<p style="color: red;" id="payment_error"></p>
JS:
function payment_validation() {
var radio_value = "",
radios = document.getElementsByName("payment");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
radio_value = radios[i].value;
break;
}
}
if (radio_value != "") {
document.getElementById("payment_error").innerHTML = "";
return true;
} else {
document.getElementById("payment_error").innerHTML = "Please select radio";
return false;
}
}
Codepen: http://codepen.io/anon/pen/avXGeK
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.