Home > Software engineering >  javascript search has no effect
javascript search has no effect

Time:11-13

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 a browser it has no effect.

What am I missing?

CodePudding user response:

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

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

CodePudding user response:

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>
  • Related