Geekender
Geekender

Reputation: 809

Show/Hide DIV on ASP.NET dropdown value change

I have the following dropdown on my ASP.NET page:

<asp:DropDownList ID="selectAttending" runat="server">
              <asp:ListItem Value="Select One...">Select One...</asp:ListItem>
              <asp:ListItem Value="Yes">Yes</asp:ListItem>
              <asp:ListItem Value="No">No</asp:ListItem>
            </asp:DropDownList>

I also have the following script:

$(function (){
$("#selectAttending").change(function () { 
ToggleDropdown(); 
}); 
ToggleDropdown();  
}); 

function ToggleDropdown(){
if ($("#selectAttending").val() == "No") {
    $("#ifAttending").hide(); 
} 
else{
    $("#ifAttending").show(); 
 } 
}; 

The DIV tag I would like to show if they are attending is: #ifAttending

Do I need to add an attribute to the dropdown to show/hide on change or is the code just wrong?

Upvotes: 2

Views: 4838

Answers (4)

DadViegas
DadViegas

Reputation: 2291

You are in .net so the identifier in jquery is not #selectAttending unless you are using clientidmode="static" if not your identifier will be in .net selectAttending.UniqueID

Upvotes: 2

Joel
Joel

Reputation: 196

The issue is that selectAttending is the control id used in the ASP code behind page and not the id of the dropdown element in the html.

You'll have to do this to get the client id of the control:

$(function (){
    $("#<%=selectAttending.ClientID%>").change(function () { 
        ToggleDropdown(); 
    }); 
    ToggleDropdown();  
}); 

function ToggleDropdown(){
    if ($("#<%=selectAttending.ClientID%>").val() == "No") {
        $("#ifAttending").hide(); 
    } 
    else{
        $("#ifAttending").show(); 
    } 
 }; 

Upvotes: 4

Mark Brackett
Mark Brackett

Reputation: 85685

The code looks about right. My guess is the ID of your DropDownList on the client isn't exactly selectAttending because of naming containers.

You can use a css class name, or get the ClientID with syntax like:

$("#<%=selectAttending.ClientID%>")

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

Although your code should work but you can simplify and try this code. Note that I am using jQuery toggle method which takes a boolean parameter to show/hide the element.

$(function (){
   $("#selectAttending").change(function () { 
       $("#ifAttending").toggle(this.value == "Yes")
   })
   .change();//trigger the change event on page load
});

Upvotes: 1

Related Questions