p.streef
p.streef

Reputation: 3815

JQuery remove elements with id not containing a string

I'm trying to implement a search algorithm on a page.

I have a table with orders, each row has an order, which has a unique ID.

Each row's <tr> has this ID set:

<tr class="searchable" id="bla_1">1</tr>
<tr class="searchable" id="bla_2">2</tr>
<tr class="searchable" id="notbla_3">3</tr>
<tr class="searchable" id="not_4">4</tr>

I would like to hide all the elements of class searchable which are unlike a search string. Preferably without just looking at the start. So in the example above, if my search string is "bla" it would show rows 1, 2 and 3.

I would also like to be able to use this same function on other containers, like divs:

<div class="searchable" id="bla_1">1</div>
<div class="searchable" id="bla_2">2</div>
<div class="searchable" id="notbla_3">3</div>
<div class="searchable" id="not_4">4</div>

I'm presuming I need some sort of a foreach loop, but so far I've not been able to find how to go about doing this.

Upvotes: 1

Views: 1382

Answers (4)

amitguptageek
amitguptageek

Reputation: 537

var search; //holds the value
if(search == ""){
  $('.searchable').show();
}else{
  $('.searchable').hide();
  $('.searchable[id*="' + search + '"]').show();
}

Upvotes: 2

Tom B.
Tom B.

Reputation: 2962

// Hide all elements containing bla in the id
$('.searchable[id*="bla"]').hide();
// Hide all elements not containing bla in the id
$('.searchable:not([id*="bla"])').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="searchable" id="bla_1">1</div>
<div class="searchable" id="bla_2">2</div>
<div class="searchable" id="notbla_3">3</div>
<div class="searchable" id="not_4">4</div>

Upvotes: 1

Muhammad Atif
Muhammad Atif

Reputation: 1102

Try this one

var search="bla";
$('.searchable').hide();
$('.searchable[id*="' + search + '"]').show();

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74420

You want to use attribute 'contains' selector.:

$('.searchable[id*="' + searchString + '"]').show();

Where searchString is a variable string equals to what string you are searching for.

Upvotes: 2

Related Questions