In your filter function, you could just generate all your html there, but I would prefer to keep them seperate. It looks to me like you have 3 different pieces:
- Your data
- A filter function to filter the data based off the search term
- An HTML generator function that will generate your html based off your data
Here’s a quick way of bringing it all together
const items = [{
name: 'toy1',
price: '12.00',
quantity: 12
},
{
name: 'toy2',
price: '1.00',
quantity: 5
},
{
name: 'toy3',
price: '11.00',
quantity: 2
},
{
name: 'toy4',
price: '1.00',
quantity: 2
}
];
/**
* Create a function to generate your elements based
* off the passed in array of data
*/
function makeList(data) {
// Grab your container
const container = document.getElementById('items');
// Clear it (reset it)
container.innerHTML = '';
// Iterate through your data and create the elements
// and append them to the container
data.forEach(i => {
const element = document.createElement('div');
element.innerText = i.name;
container.append(element);
});
}
/**
* Create an event listener to react to
* search updates so you can filter the list.
* keyUp is used so that you wait for the
* user to actually finish typing that specific
* char before running. Otherwise, you'll be missing
* a char. (Try changing it to 'keypress' and see what happens)
*/
document.getElementById('search').addEventListener('keyup', function(e) {
// Get the textbox value
const searchTerm = e.target.value;
// If no value, reset the list to all items
if (!searchTerm) {
makeList(items);
return;
}
// Filter your list of data
// based off the searchTerm
const data = items.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()));
// Pass the list filtered list of data to your makeList function
// to generate your html
makeList(data);
});
// Generate your initial list
makeList(items);
<input type="text" id="search">
<div id="items"></div>
Alternatively, you could just hide the elements in the DOM instead of regenerating a fresh html list each time.