验证下拉列表,jQuery不起作用



我在表格中有一个下拉列表,其中包含一个空白项目,如果在下拉列表中选择该空白项目时按下按钮,我希望在标签中显示错误消息

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownListParedesinteriores_ItemChanged">
<asp:ListItem Text="" Value="-1"></asp:ListItem>
<asp:ListItem Value='5'>Excellent</asp:ListItem>
<asp:ListItem Value="4">Very good</asp:ListItem>
<asp:ListItem Value="3">Good</asp:ListItem>
<asp:ListItem Value="2">Bad</asp:ListItem>
<asp:ListItem Value="1">Very bad</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label9" runat="server" Text=""></asp:Label>

这是我的J查询

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function ()
{
$("#Button1").click(function ()
{
var a = $("#<%= DropDownList1.ClientID %>");
if (a.val() === "-1")
{
document.getElementById("Label9").innerHTML = "<b>Please select an option</b>";
document.getElementById("Label9").style.color = "red";
}
else
{
document.getElementById("Label9").innerHTML = "<b>Comfirmed</b>";
document.getElementById("Label9").style.color = "green";
}
})
})
</script>

首先,此按钮是一个服务器端按钮,您必须使用 onClientClick="return false" 禁用 postaback 才能使其在客户端工作。其次,为了使用 Button1 作为 id($("#Button1"((,您需要将 ClientIDMode 更改为静态 与标签相同

<asp:Button ID="Button1" runat="server" Text="Button"  onClientClick="return false"  ClientIDMode="Static" />
<asp:Label ID="Label9" runat="server" Text="" ClientIDMode="Static"></asp:Label>

如果您不想使用静态客户端 ID,则必须替换

$("#Button1") with  $("#<%= Button1.ClientID %>")   
document.getElementById("Label9") with document.getElementById("<%= Label9.ClientID %>")

您的按钮 1 选择器 "$("#Button1(.click" 单击事件不像您的下拉列表那样考虑客户端 ID。 如果 jquery 没有找到按钮 1 的任何内容并且 click 事件从未被触发,这可能会导致问题。

一个可能的解决方法是将选择器更改为与使用 jquery 获取下拉列表的行中的选择器相同。

最新更新