SEOClerks

Improve my Javascript code for a search table function.

Improve my Javascript code for a search table function.

I have a search bar that will filter results in a table.
I would like the script to ignore any words in the search bar that do not match a keywords or items.


[Search Bar]

Item1Keyword1
Item2Keyword2
Item3Keyword3 Keyword4

Working
  • Search: "Item1" will display Item1 row
  • Search: "Keyword3" will display Item3 row
  • Search: "Keyword4 Keyword3" will display Item3 row

Not Working (please help me fix this)
  • Search: "Keyword1 Keyword3" will display Item1 and Item3 row
  • Search: "Keyword1 hello world" will display Item1 row

HTML
<input type="text" id="search" placeholder="Type to search">

<table id="table">

<tr>

<td>Item1</td>

<td>Keyword1</td>

</tr>

<tr>

<td>Item2</td>

<td>Keyword2</td>

</tr>

<tr>

<td>Item3</td>

<td>Keyword3 Keyword4</td>

</tr>

</table>

<br>

<b>Working</b>

<p>Search: "Item1" will display Item1 row (working)</p>

<p>Search: "Keyword3" will display Item3 row (working)</p>

<p>Search: "Keyword4 Keyword3" will display Item3 row (working)</p>

<br>

<b>Not Working (please help me fix this)</b>

<p>Search: "Keyword1 Keyword3" will display Item1 and Item3 row (not working)</p>

<p>Search: "Keyword1 hello world" will display Item1 row (not working)</p>

Javascript Jquery

var $rows = $('#table tr');

$('#search').keyup(function() {



var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*
,

reg = RegExp(val, 'i'),

text;



$rows.show().filter(function() {

text = $(this).text().replace(/\s+/g, ' ');

return !reg.test(text);

}).hide();

});


Requirements

Fix the search bar so I can search...

  • Search: "Keyword1 Keyword3" will display Item1 and Item3 row
  • Search: "Keyword1 hello world or any other words not found in table" will display Item1 row.
  • You can edit the code, or re-write all of the code.
  • You can use Javascript or Jquery.


Skills Required

javascript jquery

Bids

No bids made yet - be the first!

Bid On Listing

Bid On Listing Created 2 years ago in Programming

Other jobs by brandonberner