0

以下是验证带有单选按钮、文本框和下拉列表的表单的代码。用于验证单选按钮和文本框的 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>
4

2 回答 2

1
if(sex[i].checked)
{
checked = sex[i];
return true;
}

Remove return true above.
于 2013-06-21T06:46:02.530 回答
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

http://www.w3schools.com/jsref/prop_option_value.asp

于 2013-06-21T06:46:48.380 回答