Benjamin Carafa
Benjamin Carafa

Reputation: 633

jQuery elements with dataset

I would like to filter elements based on their dataset. I created a fiddle to show where I'm at: here But as you can see when I select for example 'red' it simply hides the 'red' item and not the rest. As with for example 'yellow' it won't do anything.

Here's the script:

// Filter by color
$(document).on('change', 'input', function(){
  const color_value = this.value;
  let $products = $('li').hide();
  let $filtered = $products.filter((i, el) => el.dataset.color !== '' && el.dataset.color.indexOf(`-${color_value}-`));
  $filtered.show();
});

Thanks a lot!

Upvotes: 0

Views: 27

Answers (1)

Mamun
Mamun

Reputation: 68933

Instead of indexOf() you can use includes().

Change:

el.dataset.color.indexOf(`-${color_value}-`)

To:

el.dataset.color.includes(`-${color_value}-`)

$(document).on('change', 'input', function(){
  const color_value = this.value;
  let $products = $('li').hide();
  let $filtered = $products.filter((i, el) => el.dataset.color !== '' && el.dataset.color.includes(`-${color_value}-`));
  $filtered.show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="red" id="red" name="color">
<label for="red">Red</label>
<input type="radio" value="blue" id="blue" name="color">
<label for="blue">Blue</label>
<input type="radio" value="purple" id="purple" name="color">
<label for="purple">purple</label>
<input type="radio" value="yellow" id="yellow" name="color">
<label for="yellow">yellow</label>

<ul>
  <li data-color="-red--yellow-">
    Red and yellow thing
  </li>
  <li data-color="-blue-">
    Blue thing
  </li>
  <li data-color="-purple--red-">
    Purple and red thing
  </li>
</ul>

Upvotes: 1

Related Questions