Quiero buscar en la tabla HTML con sus valores de columna mínimo y máximo y mostrar la fila buscada en la tabla. He creado un código para esto y funciona bien hasta cierto punto. Pero incluso cuando busco 2, 4, 7 en la tabla de búsqueda, sigue buscando 10-20, 30-40 y 60-70 respectivamente. Por favor, eche un vistazo y sugiérame qué debo cambiar para que funcione perfecto.
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>En su código, las variables txtValue, txtValue2 y input son todas cadenas. Utilice la función Number() para asegurarse de que las variables input y txtValue sean números.
a = "20" //this is how number as string is input aNum = Number(a) OR aNum = parseInt(a, 10)entonces puede realizar correctamente las operaciones de comparación mínima y máxima y no obtendrá 20 cuando ingrese 2.
Todo lo que necesita es parseInt() cuando está comparando datos. Normalmente, cuando obtiene valores usando etiquetas JS, devuelve String , por lo que es bastante obvio que necesita convertirlos en Integer antes de comenzar a usarlos para comparaciones.
Aquí hay un jsfiddle que funciona para su respuesta: https://jsfiddle.net/exnak6vj/1/
Alternativamente, solo una condición if más y todos los datos en la tabla se mostrarán si no hay texto en el área de texto de búsqueda. También lo he implementado en el jsfiddle anterior.
Fuera de tema: esto es bueno siempre que lo haga para su propio aprendizaje, pero para implementar algo como esto en un proyecto real, hay muchos complementos de JS disponibles en el mercado que también son gratuitos como Datatables ... etc. Úselos, le brindan una gran flexibilidad.