gpt4 book ai didi

javascript - 下拉列表验证不起作用

转载 作者:行者123 更新时间:2023-12-02 18:36:58 25 4
gpt4 key购买 nike

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

最佳答案

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

Remove return true above.

关于javascript - 下拉列表验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17229009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com