Reputation: 23
I have two dropdown lists, both of them listing the same countries. I want to display an alert message when the user selects the same country on both dropdowns. How can I do that using 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>
Upvotes: 0
Views: 146
Reputation: 5585
The way you have it is basically on the right track. Except for 2 things:
The end result would look something like:
$(document).ready(function () {
$('#ddlCountry, #ddlCountry1').on('change', function() {
if ( $('#ddlCountry').val() === $('#ddlCountry1').val() ) {
alert('Please select different countries');
}
});
});
Upvotes: 0
Reputation: 36
Do you mean you want to show dialog window? If so, you can see the code below. You can check out the API Documentation. Also, you need to check both dropdowns when the selection is changed.
<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>`
Upvotes: 0
Reputation: 4903
I think your code don't have any so issues but try this:
$(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");
}
});
});
Upvotes: 0