Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize this jQuery code?

Tags:

jquery

Been tinkering with some code regarding setting the visibility of a drop down based on the selected value of another dropdown.

This code is for the page load:

     $(document).ready(function() {
            if ($("#<%=ddlCoverage.ClientID %>").val()  == 'Basic') {
                $('#CoverageType').show();
            }
            else{
                $('#CoverageType').hide();
            }
        });

Here is the the other piece that I use for the changing of the dropdown.

$("#<%=ddlCoverage.ClientID%>").change(function() {
                $('#CoverageType')[($(this).val() == 'Basic') ? 'show' : 'hide']()
            });

Is there a better way to write this?

like image 676
Todd Avatar asked Feb 06 '26 08:02

Todd


2 Answers

http://api.jquery.com/toggle/

$('#CoverageType').toggle($("#<%=ddlCoverage.ClientID %>").val()  == 'Basic'); //true or false
like image 156
js1568 Avatar answered Feb 07 '26 21:02

js1568


If you want to toggle elements' visibility based on the selection of a drop-down, you'll also need to change the rest of you code a little:

$(function()
{
  $("#<%=ddlCoverage.ClientID %>").change(function()
  {
    $('#CoverageType').toggle($(this).val()  == 'Basic');
  });
});

This way, it'll trigger every time the drop down menu's value is changed as opposed to once when the pages loads. If you only want it when the page loads, why don't you just set it programatically in your ASP/PHP instead of JavaScript?

like image 26
Francois Deschenes Avatar answered Feb 07 '26 20:02

Francois Deschenes