Pixel
Pixel

Reputation: 15

Hide Asp:DropDownList based on select dropdownlist values?

I'm trying to hide two dropdownlists based on a value from the "Select" dropdownlist. The to ddlists i want to hide is the Asp:DropDownLists. The select class looks like this:

<select class="form-control" id="number_rooms">
             <option>1</option>
             <option>2</option>
</select>

When the value is 1, the dropdownlists should be hidden. When the value is 2, the users should see them.

Code:

<asp:DropDownList ID="droplist1" CssClass="form-control" runat="server">
              <asp:ListItem>2</asp:ListItem>
              <asp:ListItem>1</asp:ListItem>   
</asp:DropDownList>

<asp:DropDownList ID="droplist2" CssClass="form-control" runat="server">
              <asp:ListItem>2</asp:ListItem>
              <asp:ListItem>1</asp:ListItem>   
</asp:DropDownList>

Have tried some Jquery from former posts, but none seem to work..

JQuery code:

        $(function () {
            $("#number_rooms").change(function() {
                $("#droplist1").hide();
                $("#droplist2").hide();
            });
        });

Have also tried this:

        $(function () {
            if ($("#number_rooms").val() == 1) 
                $("#droplist1").hide();
                $("#droplist2").hide();
        });

The value is 1 at default, so at page loadup it should be hidden, and if a user select value = 2 , it should be shown.

Hope someone can see what i am doing wrong.

Upvotes: 0

Views: 1361

Answers (1)

Juan
Juan

Reputation: 5050

when your asp:DropDownList gets rendered its id changes to include the id of the container or containers

So your DropDownList could be rendering with an id like this

<select class="form-control" id="mycontainer_droplist1">
    <option>...</option>
</select>

You can get the correct Client ID by using

$("#<%= droplist1.ClientID %>").hide();
$("#<%= droplist2.ClientID %>").hide();

Or you can change the declaration of the asp:DropDownList to make its ID static and avoid having its container ids setting the ClientIDMode this its the default id generation

The ClientID value is generated by concatenating the ID values of each parent naming container with the ID value of the control. In data-binding scenarios where multiple instances of a control are rendered, an incrementing value is inserted in front of the control's ID value. Each segment is separated by an underscore character (_).

<asp:DropDownList ClientIDMode="static" ID="droplist2" CssClass="form-control" runat="server">
    <asp:ListItem>2</asp:ListItem>
    <asp:ListItem>1</asp:ListItem>   
</asp:DropDownList>

Static : The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.

Upvotes: 1

Related Questions