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. F I checked other StackOverflow questions but it is not answered as I expected. Can anyone help me, please?
HTML CODE:
<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>
JavaScript Code - or Example, if I search 500 then the result should come 500, 520. I mean must be greater then and equal to the number which I put in search field.
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";
}
}
}
}
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>