2014-08-28 37 views
0

我有兩個下拉列表,他們都列出了相同的國家。當用戶在兩個下拉列表中選擇相同的國家時,我想顯示一條警報消息。我怎樣才能使用jQuery?如何使用jquery在c#中顯示alertbox?

<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> 
+1

什麼是生成的代碼? C#與此無關。 – 2014-08-28 02:14:40

+0

JQuery和C#沒有關係。你在說什麼?? – 2014-08-28 02:21:48

回答

0

你擁有它的方式基本上是正確的。除了2件事:

  1. 您應該在兩個下拉列表中檢測到更改事件。
  2. 假設兩個下拉選項的值和文本都相同,您只需檢查每個選項的.val()。

最終的結果看起來是這樣的:

$(document).ready(function() { 
    $('#ddlCountry, #ddlCountry1').on('change', function() { 
     if ($('#ddlCountry').val() === $('#ddlCountry1').val()) { 
      alert('Please select different countries'); 
     } 
    }); 
}); 
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"); 
     } 
    }); 
}); 
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>` 
+0

只是代碼不是答案,請參閱[如何寫出一個好答案](http://stackoverflow.com/help/how-to-answer) – 2014-08-28 02:46:08

1

問題是您的dropdownlist將autopostback設置爲true。