I'm running a PHP file that uses javascript to add to a list of items that is pulled from a sql database. The search filter does not affect the items that were taken from the sql database. How can I get the sql items added to the ul
so that it properly gets filtered?
Index.php, the html that has the "hardwired" items- items 1 and 2
<section>
<h2>Item Selection</h2>
<form>
<input type="text" id="itemSearch" placeholder="Search for items">
</form>
<ul id="itemList">
<li>
<span>Item 1</span>
</li>
<li>
<span>Item 2</span>
</li>
</ul>
</section>
Index.php, php code that adds the items from sql to the ul
fetch('get_data.php')
.then(response => response.json())
.then(data => {
const itemList = document.getElementById('itemList');
data.forEach(item => {
const li = document.createElement('li');
li.innerHTML = "<span></span>";
li.querySelector('span').textContent = item['ItemName'];
itemList.appendChild(li);
});
Index.php, js code that filters the list
const itemList = document.getElementById('itemList');
const items = itemList.querySelectorAll('li');
const itemSearchInput = document.getElementById('itemSearch');
// Filter item list based on search input
itemSearchInput.addEventListener('input', function() {
const searchQuery = itemSearchInput.value.trim().toLowerCase();
items.forEach(item => {
const itemName = item.querySelector('span').textContent.toLowerCase();
if (itemName.includes(searchQuery)) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
});
Move items
into the listener function, so it always gets the current set of items, rather than the items that were on the page when it first loaded (which is an empty list, since they're added dynamically).
const itemList = document.getElementById('itemList');
const itemSearchInput = document.getElementById('itemSearch');
// Filter item list based on search input
itemSearchInput.addEventListener('input', function() {
const items = itemList.querySelectorAll('li');
const searchQuery = itemSearchInput.value.trim().toLowerCase();
items.forEach(item => {
const itemName = item.querySelector('span').textContent.toLowerCase();
if (itemName.includes(searchQuery)) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
});