2013-06-21 136 views
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> 
+0

上請詳細說明 「不工作」。 –

回答

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

Remove return true above.