GEM-I'm a dedicated Wordpress & Squarespace developer

How can I filter dropdown select option with using jQuery?

HTML CODE

<select class="type">
  <option value="all">all months</option>
  <option value="january">january</option>
  <option value="feburary">feburary</option>
  <option value="march">march</option> 
  <option value="june">june</option>  
</select>

<select class="Years"> 
<option value="all">All Year</option>  
  <option value="2023">2023</option> 
  <option value="2022">2022</option>
  <option value="2021">2021</option>
  <option value="2020">2020</option> 
</select>

<div class="news-load-section">
  <div class="news-item" data-Years="2023" data-type="january" data-bed="2023">2023</div>
  <div class="news-item" data-Years="2023" data-type="june" data-bed="2023">2023</div> 
  <div class="news-item" data-Years="4" data-type="feburary" data-bed="2022">2022</div>
  <div class="news-item" data-Years="3" data-type="march" data-bed="2021">2021</div> 
  <div class="news-item" data-Years="2020" data-type="feburary" data-bed="2020">126</div>
  <div class="news-item" data-Years="1" data-type="january" data-bed="2023">2023</div>
</div>

JQUERY CODE

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

//call the same function for each select's change event
$("select.type, select.Years").change(updateNEWS);

function updateNEWS() {
  //get all the values
  var newsmonth = $('select.type').val();
  var newsyear = $('select.Years').val();
  
  $('.news-load-section')
    .find('.news-item')
    .hide()
    .filter(function () {

      var oknewsmonth = true;
      if(newsmonth !== "all"){
        oknewsmonth = $(this).attr('data-type') === newsmonth;
      }

      var oknewsyear = true;
      if(newsyear !== "all"){
        oknewsyear = $(this).attr('data-bed') === newsyear;
      }

      //only fade if it satisfies all two conditions
      return oknewsmonth && oknewsyear;
  }).fadeIn('fast');
}
</script>

LIVE WORKING EXAMPLE

2023
2023
2022
2021
126
2023
Spread the Code

GEM

GEM

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *