如何使用jquery在c#中显示alertbox

本文关键字:显示 alertbox 何使用 jquery | 更新日期: 2023-09-27 18:19:48

我有两个下拉列表,它们都列出了相同的国家。当用户在两个下拉列表中选择相同的国家时,我想显示一条警告消息。如何使用jQuery做到这一点?

<td>
    <asp:DropDownList ID="ddlCountry" runat="server"   AutoPostBack="True">
    </asp:DropDownList>
</td>
<td>
    <asp:DropDownList ID="ddlCountry1" runat="server" AutoPostBack="True">
    </asp:DropDownList>
</td>
<script type="text/javascript">
     $(document).ready(function () {
         $("#<%=ddlCountry.ClientID %>").change(function () {
         if ($("#<%=ddlCountry.ClientID%> option:selected").text() == $("#<%=ddlCountry1.ClientID%> option:selected").text()) 
             {
                 alert("Please select different countries");
             }
         });
     });
</script>

如何使用jquery在c#中显示alertbox

问题是您的dropdownlist的autopostback设置为true。

我认为您的代码没有任何这样的问题,但尝试一下:

$(document).ready(function () {
    $("#<%=ddlCountry.ClientID %>, #<%=ddlCountry1.ClientID %>").change(function () {
        if ($("#<%=ddlCountry.ClientID %> option:selected").val() == $("#<%=ddlCountry1.ClientID %> option:selected").val())
        {
            alert("Please select different countries");
        }
    });
});

您的意思是要显示对话框窗口吗?如果是这样,您可以看到下面的代码。您可以查看API文档。此外,在更改选择时,还需要同时检查两个下拉菜单。

<td>
    <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True">
    </asp:DropDownList>
</td>
<td>
    <asp:DropDownList ID="ddlCountry1" runat="server" AutoPostBack="True">
    </asp:DropDownList>
</td>
<script type="text/javascript">
$(document).ready(function() {
    $("#<%=ddlCountry.ClientID %>").change(function() {
        if ($("#<%=ddlCountry.ClientID%> option:selected").text() == $("#<%=ddlCountry1.ClientID%> option:selected").text()) {
            $( "#dialog" ).dialog({
  dialogClass: "no-close",
  buttons: [
    {
      text: "OK",
      click: function() {
        $( this ).dialog( "close" );
      }
    }
  ]
});
        }
    });
});
</script>
<div id="dialog" title="Alert">
    <p>Please select different countries</p>
</div>`

您拥有它的方式基本上是正确的。除了两件事:

  1. 您应该在两个下拉列表中都检测到更改事件
  2. 假设下拉选项的值和文本在两者中都相同,您只需要检查每个选项的.val()

最终结果看起来像:

$(document).ready(function () {
    $('#ddlCountry, #ddlCountry1').on('change', function() {
        if ( $('#ddlCountry').val() === $('#ddlCountry1').val() ) {
            alert('Please select different countries');
        }
    });
});