Said
Said

Reputation: 186

Simplify a Jquery filter script

Can this script be simplified so that I don't have to specifically define the class attr just in case there are additional types added.

The JQuery

$(".devfilter select").change(function(){
  $( ".devfilter select option:selected").each(function(){
      if($(this).attr("value")==="Current"){
          $(".property.Upcoming").fadeOut("slow");
          $(".property.Completed").fadeOut("slow");
          $(".property.Current").fadeIn("slow");
        }
      if($(this).attr("value")==="Upcoming"){
          $(".property.Current").fadeOut("slow");
          $(".property.Completed").fadeOut("slow"); 
          $(".property.Upcoming").fadeIn("slow");
        }
      if($(this).attr("value")==="Completed"){
          $(".property.Current").fadeOut("slow");
          $(".property.Upcoming").fadeOut("slow");
          $(".property.Completed").fadeIn("slow");
      }
      if($(this).attr("value")==="*"){
          $(".property.Current").fadeIn("slow");
          $(".property.Upcoming").fadeIn("slow");
          $(".property.Completed").fadeIn("slow");
      }
  });
}).change();

The HTML

<p class="devfilter">
<select name="development-filter">
    <option value="*">All</option>
    <option value="Current">Current</option>
    <option value="Upcoming">Upcoming</option>
    <option value="Completed">Completed</option>

<div class="more classes property Upcoming" data-type="Upcoming">Upcoming 1</div>
<div class="more classes property Current" data-type="Current">Current 1</div>
<div class="more classes property Completed" data-type="Completed">Completed 1</div>
<div class="more classes property Completed" data-type="Completed"> Completed  2</div>
<div class="more classes property Upcoming" data-type="Upcoming">Upcoming 2</div>
<div class="more classes property Current" data-type="Current">Current 2</div>

Thanks Said

Upvotes: 1

Views: 33

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

As the select is not allowing multiple selections, there is no need to use $.each on the options, you can retrieve the selected option using val() and then build the selector like this:

$(".devfilter select").change(function() {
    $(".property").fadeOut("slow");
    var value = $(this).val();
    var selector = value == '*' ? '.property' : '.property.' + value;
    $(selector).fadeIn("slow");
}).change();

Example fiddle

Upvotes: 2

Sudharsan S
Sudharsan S

Reputation: 15393

Try this

$(".devfilter select").change(function(){

  $( ".devfilter select option:selected").each(function(){

          $(".property").fadeOut("slow");
          $(".property"+"."+$(this).data("type")).fadeIn("slow");

  });
}).change();

Upvotes: 0

Related Questions