我想避免使用for
循环来验证一组单选按钮。我知道可以使用它们的布尔值来执行此操作我似乎无法执行它。有更好的方法吗?
以下是我的按钮:
<form method="post" name="newUser" onsubmit="return proc()">
First name:<br />
<input type="text" id="fName" /><br />
<div id="first_name_error"></div>
Last name:<br />
<input type="text" name="lName" /><br />
<div id="last_name_error"></div>
E-mail address:<br />
<input type="text" name="eMail" /><br />
<div id="email_error"></div>
Gender:<input type="radio" name"sex" value="male" />Male
<input type="radio" name="sex" value="female" />Female<br />
<div id="gender_error"></div>
这是我的JS:
function proc(){
var errmsg = "";
if (document.forms["newUser"]["fName"].value == "")
{
document.getElementById('first_name_error').innerHTML = "*This field is required";
document.getElementById('first_name_error').style.color = "red";
}
if (document.forms["newUser"]["lName"].value == "")
{
document.getElementById('last_name_error').innerHTML = "*This field is required";
document.getElementById('last_name_error').style.color = "red";
}
if (document.forms["newUser"]["eMail"].value == "")
{
document.getElementById('email_error').innerHTML = "*This field is required";
document.getElementById('email_error').style.color = "red";
}
if (document.forms["newUser"].sex == false)
{
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
}
return false;
}
答案 0 :(得分:2)
我认为你最好将两个ID分配给两个单选按钮(例如radbtnMale,radbtnFemale) 然后检查:
if (document.getElementById("radbtnMale").checked == false && document.getElementById("radbtnFemale").checked == false) {
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
} else {
//
}
答案 1 :(得分:0)
试试这个(jQuery):
if($('input[name=n]:checked').length==0){
//error
}else{
//OK
}