Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery hide table column not containing value

I'm trying to hide a row in a table if it does not contain a search value.

This works:

<table class="mytable">
    <tr>
        <td>1001</td>
        <td>apples</td>
    </tr>
    <tr>
        <td>1002</td>
        <td>bananas</td>
    </tr>
</table>
<button id="mybutton">Button</button>
<button id="mybutton2">Button2</button>

This will work by hiding all rows, then showing the ones we want:

$('#mybutton').click(function(){
    $('.mytable td').parent().hide();
    $('.mytable td:contains("apples")').parent().show();
});

But I've seen there's a more elegant (and probably efficient) solution using :not selector, but I can't get it working:

$('#mybutton2').click(function(){
    $('.mytable td:not(:contains("apples"))').parent().hide();
});

How can I get this working using the :not selector, so that if a row does not contain apples, it will be hidden, leaving all the rows that contain apples.

JS Fiddle: https://jsfiddle.net/ryy3tvob/

like image 710
Jonathan Clark Avatar asked Feb 15 '26 01:02

Jonathan Clark


1 Answers

Because first td not contains apple in any row and it will select all first td so it will hide it's parent. So you need to use :contains() for tr

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected. ( Taken from https://api.jquery.com/contains-selector/ )

$('#mybutton2').click(function() {
  $('.mytable tr:not(:contains("apples"))').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="mytable">
  <tr>
    <td>1001</td>
    <td>apples</td>
  </tr>
  <tr>
    <td>1002</td>
    <td>bananas</td>
  </tr>
</table>
<button id="mybutton">Button</button>
<button id="mybutton2">Button2</button>
like image 152
Pranav C Balan Avatar answered Feb 16 '26 13:02

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!