I am developing a site that contains a live search. This live search is used to search for contacts in a contact list (An HTML table). The contact list is a table with 2 columns, with each column containing a contact. The search works but, it returns the whole row, not just the matching columns.
Meaning that if I search for A in a table like the one in the snippet below; the search returns the whole row ( A || B ), not just A. Is there any way I could refine my function to search through columns instead of rows?
Hope I explained myself clearly.
<table> <tr> <td>A</td> <td>B</td> </tr> <tr> <td>C</td> <td>D</td> </tr> </table>
Function
<script>
function myFunction() {
//variables
var input, filter, table, tr, td, i;
input = document.getElementById("search");
filter = input.value.toUpperCase();
table = document.getElementById("table");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td)
{
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
I've modified your code to iterate all the td
elements in your table. instead of hiding the cells that don't contain the filter text I've opted to apply an opacity to them. It makes it clearer in the example what is happening.
When doing work on key down, don't forget to debounce the event. See this post for a good introduction: https://davidwalsh.name/javascript-debounce-function
function myFunction() { //variables var input = document.getElementById("search"), filter = input.value.toUpperCase(), table = document.querySelector('table'), cells = table.querySelectorAll('td'); for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (cell.innerHTML.toUpperCase().indexOf(filter) > -1) { cell.classList.remove('no-match'); } else { cell.classList.add('no-match'); } } } const form = document.getElementById('form'), input = document.getElementById("search"); form.addEventListener('submit', onFormSubmit); input.addEventListener('keyup', onKeyUp); function onFormSubmit(event) { event.preventDefault(); myFunction(); } function onKeyUp(event) { // Debounce this event in your code or you will run into performance issues. myFunction(); }
.no-match { opacity: .2; }
<form id="form"> <label> Filter text <input type="text" id="search"/> </label> <button>Filter</button> </form> <table> <tr> <td>A</td> <td>B</td> </tr> <tr> <td>C</td> <td>D</td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.