Vic
Vic

Reputation: 155

How do I get jquery script to fire on dropdown menu event?

For a filter-search I'm using a form to display a dropdown menu and I need to add or remove a class to the parent div depending on the value of the option selected from the menu.

There are at least two problems with this script: 1. It's loading with the page and adding the class immediately. I need it to run only when the user chooses an option. 2. Selecting an Option isn't updating the page. 3. Also I'm not sure if my variable $key is storing the correct value. I want the value selected from the option.

I've looked at several SO similar questions and reviewed the jquery documentation for .select(), .change() and .trigger() but I haven't put together the combination that works for my situation yet.

Below is the stripped down basic script I'm using that is effectively adding the class to the sample HTML.

<select name="SelectBox-ByDestination" id="SelectBox-ByDestination">
  <option value="" disabled selected hidden>Select a Destination...</option>
  <option value="Argentina">Argentina</option>
  <option value="Australia">Australia</option>
  <option value="Iceland">Iceland</option>
</select>

<div class="Item">
  <h3>Program</h3>
  <div class="destination">
    <h4>Destinations</h4>
    <ul>
      <li>Iceland</li>
    </ul>
  </div>
</div>

$(function () {
  $('#SelectBox-ByDestination').change(function() {
    var $dest = $(this).val();
    $('.destinations').each(function() {
      var $matches = $('.destination li').filter(function() {
        return $(this).text() === $dest
      });
      if (!$matches.length) {
        $(this).parent().addClass('hideByDestinationDropDownMenu');
      } else {
        $(this).parent().removeClass('hideByDestinationDropDownMenu');
      }
    });
  });
});

Upvotes: 0

Views: 41

Answers (1)

charlietfl
charlietfl

Reputation: 171679

First thing you need is a change event listener on the <select>

Then you want to compare it's value against the text in individual <li> elements when the event fires

$('#SelectBox-ByDestination').on('change', function() {
  var dest = $(this).val();
  $('.destinations').each(function() {
    // filter matching `<li>` 
    var $matches = $('.destintion li').filter(function() {           
      return $(this).text() === dest// or use `includes() for partial matches
    });

    if(!$matches.length){
       // hide this destination div
    }else{
       // show it
    }

  });
});

I'm guessing you want to hide other <li> also but this should get you started

Upvotes: 1

Related Questions