我在获取单选按钮值时遇到问题。我通过stackoverflow搜索并遵循相同问题的说明,但没有帮助。如果你能提供帮助我会很感激:
以下代码中的radio_value始终返回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>
&#13;
答案 0 :(得分:1)
使用.checked而不是.value。这应该有帮助,使其不是NULL。所以它会是
radio_value=radios[i].checked;
答案 1 :(得分:1)
一些事情:
payment_validation
函数返回true或false;所以删除行return radio_value
,而不只是break
。var
。<p>
标记。payment_error
id的元素,因此代码会按原样生成错误。<span>
标记格式错误;它缺少属性值周围的引号,并且在payment_error
之前有一个空格。总而言之,现在:
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;
}
}