How to search number from html table using javascript?

Viewed 248

I am having difficulty searching numbers from the HTML table using javascript. What I want to do, if I enter 500 then the results should be 500 and numbers that are also greater than 500. I checked other StackOverflow questions but it is not answered as I expected. Can anyone help me, please?

function myFunction(){
   let filter = document.getElementById('myInput').value;
   let myTable = document.getElementById('myTable');
   let tr = myTable.getElementsByTagName('tr');
   for(var i=0; i<tr.length; i++)
   {
     let td = tr[i].getElementsByTagName('td')[0];
     if(td)
     {
        let textValue = td.textContent || td.innerHTML;
        if(textValue >= filter  )
        {

          tr[i].style.display = "";

        }
        else 
        {
          tr[i].style.display = "none";

        }
     }
   }
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Number</th>
    <th style="width:40%;">Alphabats Code</th>
  </tr>
  <tr>
    <td>500</td>
    <td>ANAA</td>
  </tr>
  <tr>
    <td>520</td>
    <td>MNAAA</td>
  </tr>
  <tr>
    <td>400</td>
    <td>INNA</td>
  </tr>
  <tr>
    <td>200</td>
    <td>OISSS</td>
  </tr>
  <tr>
    <td>500</td>
    <td>QIIWS</td>
  </tr>
</table>

1 Answers

A small change to your code

if(+textValue >= +filter  )

Compare values as number instead of strings

function myFunction(){

   let filter = document.getElementById('myInput').value;
   let myTable = document.getElementById('myTable');
   let tr = myTable.getElementsByTagName('tr');
   for(var i=0; i<tr.length; i++)
   {
     let td = tr[i].getElementsByTagName('td')[0];
     if(td)
     {
       let textValue = td.textContent || td.innerHTML;
      if(+textValue >= +filter  )
      {

        tr[i].style.display = "";

      }
      else 
      {
        tr[i].style.display = "none";
      
      }

     }

   }


}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Number</th>
    <th style="width:40%;">Alphabats Code</th>
  </tr>
  <tr>
    <td>500</td>
    <td>ANAA</td>
  </tr>
  <tr>
    <td>520</td>
    <td>MNAAA</td>
  </tr>
  <tr>
    <td>400</td>
    <td>INNA</td>
  </tr>
  <tr>
    <td>200</td>
    <td>OISSS</td>
  </tr>
  <tr>
    <td>500</td>
    <td>QIIWS</td>
  </tr>

</table>

Related