Pரதீப்
Pரதீப்

Reputation: 93754

Hide/show controls based on dropdown selection

I am trying to show/hide a link in my web page based on the selected value of my drop down.

Here is my drop down and link

<asp:DropDownList ID="ddlOption" runat="server" Width="100px" onchange="templateVisbility()">
<asp:ListItem Value="Value1" Text="Value1" Selected="True"> </asp:ListItem>
<asp:ListItem Value="Value2" Text="Value2"> </asp:ListItem>
</asp:DropDownList>

<asp:HyperLink ID="Link1" runat="server" NavigateUrl="/myexcel.xlsx" Text="test template" />

JavaScript to hide/show the link

<script type="text/javascript">
    function templateVisbility() {
        var e = document.getElementById("ddlOption");
        var selectedval = e.options[e.selectedIndex].value;
        if (selectedval != 'Value1') {
            document.getElementById('Link1').style.visibility = 'hidden';
        }
        else {
            document.getElementById('Link1').style.visibility = 'visible';
        }
    }
</script>

It works as expected, but I feel I have done too much work for simple thing. Is there a better/simple approach to do this.

Upvotes: 0

Views: 132

Answers (1)

Mamun
Mamun

Reputation: 68933

There is not much you can do. You can just pass this to the function to reduce a single line:

function templateVisbility(thatObj) {
  var selectedval = thatObj.options[thatObj.selectedIndex].value;
  if (selectedval != 'Value1') {
      document.getElementById('Link1').style.visibility = 'hidden';
  }
  else {
      document.getElementById('Link1').style.visibility = 'visible';
  }
}
<select id="ddlOption" onchange="templateVisbility(this)">
  <option value="Value1">Value1</option>
  <option value="Value2">Value2</option>
</select>

<a href="#" id="Link1">Link1</a>
<a href="#" id="Link2">Link2</a>

Upvotes: 2

Related Questions