1

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 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, ProGu, Can you please tell me what plus sign do here +textValue >= +filter d?
Great. Thank you..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.