0

I want to search the HTML table with its min and max column values and display the searched row in the table. I have made a code for this and it is working fine to some extent. But even when I am searching 2, 4, 7 in the table search, it is still searching for 10-20, 30-40 and 60-70 respectively. Please take a look and suggest me what should I change so that it should work perfect.

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput").value;
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    td2 = tr[i].getElementsByTagName("td")[1];
    if (td) {
      txtValue = td.textContent || td.innerText;
      txtValue2 = td2.textContent || td2.innerText;
      if (input >= txtValue && input <= txtValue2) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search by min-max values" title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Min</th>
    <th style="width:40%;">Max</th>
    <th style="width:40%;">Output</th>
  </tr>
  <tr>
    <td>10</td>
    <td>20</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>30</td>
    <td>40</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>60</td>
    <td>70</td>
    <td>UK</td>
  </tr>
</table>

2 Answers2

1

In your code the variables txtValue, txtValue2 and input are all strings. Use Number() function to make sure input and txtValue variables are Numbers.

a = "20" //this is how number as string is input

aNum = Number(a)
OR
aNum = parseInt(a, 10)

then you can properly do min and max comparison operations and you will not get 20 when you input 2.

codefire
  • 393
  • 1
  • 3
  • 13
1

All you need is parseInt() when you're comparing data. Normally when you get values using JS tags, they returns String, so it's pretty obvious you need to covert those to Integer before start using them for comparisons.

Here's a working jsfiddle for your answer - https://jsfiddle.net/exnak6vj/1/

Alternatively, just one more if condition and all the data in the table will be displayed if there's no text in search text area. I've implemented that too in the above jsfiddle.

Off-topic - this is good as long as you're doing it for your own learnings, but to implement something like this in actual project, there are whole lot of JS plugins available in market that too for free like Datatables... etc. Use those, they provides you great flexibility.

hkhowal
  • 36
  • 3