0

I am using Javascript to search in a table of data. Now it's hardcoded.

Alright, so here is my js code:

$('#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();
});

It makes the text bar search in the table below. The table is here:

<input type="text" id="search" placeholder="Type to search">
<table id="table">
    <tr>
        <th>Naam</th>
        <th>Product -</th>
        <th>Locatie</th>
    </tr>
    <tr>
        <td>Henk</td>
        <td>Laptop</td>
        <td>Utrecht</td>
    </tr>
    <tr>
        <td>Klaas</td>
        <td>Beamer</td>
        <td>Gorinchem</td>
    </tr>
    <tr>
        <td>Sjaan</td>
        <td>Opnameapparatuur</td>
        <td>Gorinchem</td>
    </tr>
</table>

When I use the codes in JSfiddle it works, but as soon as I use it in html/php it doesn't.

My endresult is to have it work with a table created from sql data, but I need it to work with hardcoded data first to be sure.

EDIT: The JSfiddle can be found here

ThisIsNotArmand
  • 99
  • 2
  • 14

1 Answers1

2

As pointed you are trying to access the DOM before it has been loaded.

This fiddle is yours just upaded with jQuery ready function

http://jsfiddle.net/7BUmG/3393/

$(function(){
        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();
        });

});
Saar
  • 2,276
  • 1
  • 16
  • 14