如何使用jquery在c#中显示警告框?

时间:2014-08-28 02:12:33

标签: javascript c# jquery asp.net

我有两个下拉列表,它们都列出了相同的国家/地区。当用户在两个下拉列表中选择相同的国家/地区时,我想显示警告消息。我怎么能用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>

4 个答案:

答案 0 :(得分:1)

问题是您的下拉列表将autopostback设置为true。

答案 1 :(得分:0)

你拥有它的方式基本上是在正确的轨道上。除了两件事:

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

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

答案 2 :(得分:0)

我认为您的代码没有任何问题,但请尝试以下方法:

$(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");
        }
    });
});

答案 3 :(得分:0)

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

<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>`