I have this search which filters the elements directly when I type letters in the input field. And now I want to reset the search by clicking on the 'x'.
So far the filter only reacts 'live' and goes back to the initial state when I delete the letters with the backspace key. But when I click on the 'x' it just deletes my written letters. Other than that nothing happens and I have to press 'enter' in the input field to reset the search again.
But I would really love the search to reset itself (without having to press 'enter') when I click on the 'x' button.
That's my search in HTML. The span id="clear" is the 'x' button I'm talking about.
<div id="Search">
<div class="icon"></div>
<div class="input">
<input type="text" placeholder="nach AdSpecial suchen" id="adSearch" onkeyup="search_ads()">
</div>
<span id="clear" onclick="clearSearch()"></span>
</div>
And that's my JavaScript code. All my elements that I want to filter have the class '.filterDiv'.
const search = document.getElementById("Search");
const items = document.querySelectorAll(".filterDiv");
function search_ads() {
let input = document.getElementById('adSearch').value
input=input.toLowerCase();
let x = document.getElementsByClassName('filterDiv');
for (i = 0; i < x.length; i++) {
if (!x[i].innerHTML.toLowerCase().includes(input)) {
x[i].style.display="none";
}
else {
x[i].style.display="";
}
}
}
function clearSearch() {
document.getElementById('adSearch').value="";
}
This is my first post here, so I apologise if I forgot to mention some important informations!