以下是使用单选按钮,文本框和下拉列表验证表单的代码。用于验证单选按钮和文本框的javascript工作正常。但下拉列表的JavaScript不起作用。你能告诉我,我做错了什么吗?
请帮忙!
提前致谢。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var checked = null;
var name1 = document.forms["information"]["firstname"].value;
var n=name1.split(" ");
var name = n[0];
var sex = document.forms["information"]["sex"];
var e = document.getElementById("prof1");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(name == null || name== "")
{
alert('Enter First Name');
return false;
}
for (var i=0;i<2;i++)
{
if(sex[i].checked)
{
checked = sex[i];
return true;
}
}
if (checked == null)
{
alert(' Enter Sex');
return false;
}
if(strUser==0)
{
alert("Enter Profession");
return false;
}
}
</script>
</head>
<body>
<form name="information" onsubmit="return validateForm()" method="post">
<text style="color:red">*</text> First Name: <input type="text" name="firstname"><br><br>
Last Name: <input type="text" name="lastname"><br><br>
<text style="color:red">*</text> Sex: <input type="radio" name="sex" value="Male"> Male
<input type="radio" name="sex" value="Female"> Female <br><br>
<text style="color:red">*</text> Profession:
<select id="prof1">
<option value="0"> Select </option>
<option value="1"> Engineer </option>
<option value="2"> Doctor </option>
<option value= "3"> Lawyer </option>
<option value="4"> Others </option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:1)
if(sex[i].checked)
{
checked = sex[i];
return true;
}
Remove return true above.
答案 1 :(得分:1)
for ( var i = 0; i < 2; i++) {
if (sex[i].checked) {
checked = sex[i];
//return true;
}
}
取消注释return true;
循环内的return语句返回值,这导致在执行此return语句后写入的代码不执行。
2
if(strUser==0)
替换为
if(strUser=="0")
原因:
http://www.w3schools.com/jsref/prop_select_selectedindex.asp