0

I was trying to get a searchable html table.

Based on the accepted answer here and the demo here I thought including the search script with <script></script> should work:

<input type="text" id="search" placeholder="Type to search">
<table id="table">
   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

<script>
var $rows = $('#table tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    
    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});
</script>

The above snippet does work when I try it on jsfiddle. But if I write this to an html locally and open it in a browser it has no effect.

What am I missing?

the.real.gruycho
  • 608
  • 3
  • 17

2 Answers2

1

It seems you need jquery. Adding this will fix it:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Inspecting the console log can sometimes provide information about errors.

E.g. Chromium you can view it with Ctrl + Shift + I and with your original snippet you will see:

Uncaught ReferenceError: $ is not defined
    at test.html:18
the.real.gruycho
  • 608
  • 3
  • 17
0

Run your javascript code after page loaded by wrapping like this:

window.addEventListener('load', function () {
   // your js code here
})
karakale
  • 126
  • 11