'Search filter not working when loading content added dynamically via fetch() or AJAX load()
I'm using a simple search filter to filter several links that I have.
The script looks like this:
var input = document.getElementById("search-filter-cards");
input.addEventListener("input", myFunction);
function myFunction(e) {
var filter = e.target.value.toUpperCase();
var list = document.getElementById("links-list");
var divs = list.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
var a = divs[i].getElementsByTagName("a")[0];
if (a) {
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
divs[i].style.display = "";
} else {
divs[i].style.display = "none";
}
}
}
}
The HTML:
<button id="anchor-open-cards-list-btn">Load</button>
<input id="search-filter-cards">
<div id="links-list">
// links here
<div id="box"></div>
</div>
Sample link:
<div class="card link-container">
<img src="assets/links.png"/>
<a class="link-title" href="#">SAMPLE LINK</a>
</div>
This search filter works fine if I don't load the content dynamically. But since there's hundreds of them, I used fetch() first, then AJAX load() to improve the page's loading speed.
The problem then is, the filter doesn't work anymore when I do so.
I fetch it onclick of a button using a simple script..
fetch()
function fetchMainMenuQuickLinks() {
fetch('../components/main-menu-quick-links.html')
.then(response => response.text())
.then(text => document.querySelector('#component-main-menu-quick-links').innerHTML = text);
}
I also tried AJAX load()
$(document).ready(function(){
$("#anchor-open-cards-list-btn").click(function(){
$("#box").load("test-content.html");
});
});
These two loads the content sure, but the search filter is no longer working by doing so..
The only alternative I can think of that I can pull is a simple document.write(), but I wouldn't prefer that..
How do I fix such an issue? I'm still new in learning JS and I don't know every workaround..
I believe my problem is the same as this: Filter/search function not targetting dynamically added rows. But I tried the solution they posted but it didn't work either for my case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
