javascripthtmljquerylivesearch

Search realtime with submit button


I want to make a realtime search using jquery and a little vanilla javascript, I tried the code below :

HTML

<input type="text" id="myInput" placeholder="Type to search">
<button type="button" onclick="searchKey()">Serch</button>
<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>

JAVACRIPT

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

but instead the contents in the table disappear and don't work, but when I'm empty, then click submit again, the contents appear again, I want to fit the search, for example "p" comes out the contents that have the letter "p" when I click the submit button. and I want when I delete the search input, all the contents in the table immediately appear again without clicking the submit button.


Solution

  • You can hide and show the element if the text is present in the td using by adding/removing the CSS class hide

    const rows = document.querySelectorAll("table tr");
    
    function searchKey() {
      var val = $.trim($('#myInput').val()).replace(/ +/g, ' ').toLowerCase();
      
      rows.forEach(row => {
        const elements = [...row.children];
        if (!elements.some(el => el.textContent.toLowerCase().includes(val)))
          row.classList.add("hide");
        else row.classList.remove("hide");
      })
    }
    .hide {
      display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="myInput" placeholder="Type to search">
    <button type="button" onclick="searchKey()">Search</button>
    <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>