Hiding a div when dropdown selected value changes

2019-07-30 13:46发布

问题:

I have a dropdown list that when the selected value changes I want to hide a div. (There is another control that makes the div visible).

I currently have the following but the div is not hiding when I change the selected value in the dropdown.

<script type="text/javascript">
$(document).ready(function () {

    $('#MyDd').change(function () {
        $('#buttonDiv').hide();            
    });
});

</script>

<asp:DropDownList ID="MyDd" runat="server" /> 
<div id="buttonDiv" class="buttonContainer">
    <asp:Button ID="myButton" runat="server" /> 
</div>

Any ideas why this wouldn't be working?

Thanks in advance for your help.

回答1:

The Id of the server side controls of Asp.net changes when the page is rendered. So "MyDd" will no longer be the Id of the drop downlist. You have to register javascript variables through code behind. Try to save the client id of the dropdown in a local variable and register the script.

You can specify a class for the dropdown and then assign an event for the element using the class.

<asp:DropDownList ID="DropDownList1" runat="server" class="cls">
   <asp:ListItem Text="One" Value="1" />
   <asp:ListItem Text="Two" Value="2" />
</asp:DropDownList>

<script type="text/javascript">
 $().ready(function () {
     $('.cls').change(function () {
         alert('hi');
     });
 });
 </script>

i used jquery here and this works.



回答2:

I guess you already understand that you need to use:

<script type="text/javascript">
$(document).ready(function () {

    $('#<%=MyDd.ClientID%>').change(function () {
        $('#buttonDiv').hide();            
    });
});

</script>

<asp:DropDownList ID="MyDd" runat="server" /> 
<div id="buttonDiv" class="buttonContainer">
    <asp:Button ID="myButton" runat="server" /> 
</div>