試試這個方法!但你可以使用asp.net驗證控件。
任何方式,我的解決方案將驗證兩點式,在下拉菜單中選擇淡水河谷或下拉列表中選擇的項目
function Validate()
{
var e = document.getElementById('<%=ddltype.ClientID%>');
//if you need value to be compared then use
var strUser = e.options[e.selectedIndex].value;
//if you need text to be compared then use
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0) **//for text use if(strUser1=="---Select---")**
{
alert("Please Select setter/getter type.");
return false;
}
}
下面的代碼已經改變你的一些代碼和工作對我好
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validation() {
debugger;
var e = document.getElementById('<%=ddltype.ClientID%>');
var strUser1 = e.options[e.selectedIndex].value;
if (strUser1 == 0) {
alert("Please Select setter/getter type.");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="validation();" OnClick="btnSave_Click" />
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
,看到這一行
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
但是你錯過了該項目的設置值,所以它出現錯誤,現在在該行設置值0,現在您的代碼工作(請參閱我的示例代碼),或者您需要使用.text
並檢查條件
if(strUser1=="---Select---")
{
//alert
}
爲什麼不使用ASP.NET驗證器? –
什麼是導致JavaScript的火災?它是在一個onclick事件?爲什麼不使用ASP.NET驗證中的構建?最少爲0的'RangeValidator'應該這樣做? – RemarkLima
您選擇的選擇沒有任何價值。做到這一點;然後它會工作 –