Sam Skirrow
Sam Skirrow

Reputation: 3697

add class to item depending on select option

I am trying to add a class to a <li> when an option is selected from a drop down menu. Here is my simplified html:

<li id="customize-control-navbar_position" class="customize-control customize-control-select">      
<label>
<span class="customize-control-title">NavBar Positioning</span>

<select data-customize-setting-link="navbar_position">
    <option value="none">None</option>
    <option value="top">Top</option>
    <option value="under-header">After Header Section</option>
    <option value="hidden" selected='selected'>Hidden</option>          
</select>
</label>
</li>

<li id="customize-control-navbar_height" class="customize-control customize-control-slider">
<label>
<span class="customize-control-title">NavBar Height</span>

    <input type="text" class="kirki-slider" id="input_navbar_height" disabled value="130" data-customize-setting-link="navbar_height"/>

</label>
</li>

Here is my JS

jQuery(document).ready(function($){

    var navbar_pos_val = $('#customize-control-navbar_position select').val();
    $("#customize-control-navbar_position").change(function() {
    if (navbar_pos_val == 'hidden') {
        $('#customize-control-navbar_height').addClass('disabled');
    }
    });

});

I'm trying to add the class "disabled" to the <li> #customize-control-navbar_height when "hidden" is selected. Currently there is some odd behavior with this code, sometimes it works when any option is selected, other times it doesn't work at all. I'm wondering if anyone can see any obvious issues with my code?

Upvotes: 0

Views: 360

Answers (2)

Eladit
Eladit

Reputation: 178

The problem is that you don't update the value of navbar_pos_val every time there's a change on the seleceted time. Try like this

jQuery(document).ready(function($)
{

    $("#customize-control-navbar_position").change(function() 
    {
         var navbar_pos_val = $('#customize-control-navbar_position select').val();
        if (navbar_pos_val == 'hidden')
        {
          $('#customize-control-navbar_height').addClass('disabled');
         }
    });

});

Upvotes: 0

yaser eftekhari
yaser eftekhari

Reputation: 235

This should fix it:

jQuery(document).ready(function($){
    $("#customize-control-navbar_position").change(function() {
      var navbar_pos_val = $('#customize-control-navbar_position select').val();
      if (navbar_pos_val == 'hidden') {
        $('#customize-control-navbar_height').addClass('disabled');
      }
    });
});

Upvotes: 2

Related Questions