Home > database >  How do I clear the filters on a filter table js
How do I clear the filters on a filter table js

Time:09-09

I added a search bar to a table with the goal of filtering the table rows. The filter function works perfectly and when I close the search bar it clears the text, but when I close the search bar the filters are not cleared and the table remains filtered until I open the search bar again and type something again. I have tried adding multiple js functions that are supposed to clear the filters when I close the search bar but nothing has worked.

Here's the js for the filtering function:

          // Declare variables
          var input, filter, table, tr, td, i, txtValue;
          input = document.getElementById("myInput");
          filter = input.value.toUpperCase();
          table = document.getElementById("myTable");
          tr = table.getElementsByTagName("tr");
        
  
          for (i = 0; i < tr.length; i  ) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
              txtValue = td.textContent || td.innerText;
              if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
              } else {
                tr[i].style.display = "none";
              }
            }
          }
        }``` 
And here is the html for the search bar:

```<form >
            <input type="text" id="myInput" onkeyup ="myFunction()" placeholder="Search for a command.."/>
            <button type="reset"></button>
        </form>```

CodePudding user response:

Maybe you didn't tried this way: you need to reset filter value on button click, like

document.getElementById('btn').addEventListener((click)=>value="")

CodePudding user response:

 // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");


        for (i = 0; i < tr.length; i  ) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    <form >
        <input type="search" id="myInput" onkeyup="myFunction()" placeholder="Search for a command.." />
        <button type="reset"></button>
    </form>

  • Related