David
David

Reputation: 39

Filter table based on select value

I have read multiple topics and couldn't find the one that suits my needs.

This is an example:

<table>
 <tbody>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>Web Developer</td>
  </tr>
<tr>
    <td>Michael</td>
    <td>Doe</td>
    <td>Web Designer</td>
  </tr>
<tr>
    <td>Nicole</td>
    <td>Doe</td>
    <td>Graphic Designer</td>
  </tr>
</tbody>
</table>

And this would be select option

<select>
<option value="developer">Developers</option>
<option value="designer">Designers/option>
</select>

So what I would need is that when "Designers" it will list only designers (graphic, web...).

How can I achieve this? Basically I'll have one option value but it will need to filter multiple table rows containing different content.

Upvotes: 0

Views: 65

Answers (1)

Zenoo
Zenoo

Reputation: 12880

You can add an attribute on your tr (here data-job) to keep track of each person's job and compare it to your option value on change of your select :

$('#jobSelect').on('change',function(){
  $('#people tr').hide();
  $('#people tr[data-job="'+$(this).val()+'"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="people">
  <tbody>
    <tr data-job="developer">
      <td>John</td>
      <td>Doe</td>
      <td>Web Developer</td>
    </tr>
    <tr data-job="designer">
      <td>Michael</td>
      <td>Doe</td>
      <td>Web Designer</td>
    </tr>
    <tr data-job="designer">
      <td>Nicole</td>
      <td>Doe</td>
      <td>Graphic Designer</td>
    </tr>
  </tbody>
</table>

<select id="jobSelect">
  <option value="developer">Developers</option>
  <option value="designer">Designers</option>
</select>

Upvotes: 1

Related Questions