I have a search feature which uses JavaScript to filter a html list.
All list items are hidden by default but show if the user inputs the right keywords.
At the moment the search only returns items which match the input exactly.
If a word is missed, additional word added or order of words differ, the result isn’t shown.
I’d like the user to be able to search multiple words, and if one or more of the words match, the result is shown.
It should not matter which order the user inputs the words.
For example, searching ‘VAUXHALL CORSA DIESEL’ would return the list item, ‘BLUE VAUXHALL CORSA 1.6L DIESEL.’
Searching ‘DIESEL VAUXHALL’ would also return the same list item.
I figured this could be done by incorporating .split(“ ”), however I am unsure at what point in the code it is needed.
I’ve tried a few configurations to no avail.
I’m very new to coding!
I’ve added the current script.
window.addEventListener("load", () => {
var filter = document.getElementById("filter"),
list = document.querySelectorAll(".list li");
filter.onkeyup = () => {
let search = filter.value.toLowerCase();
for (let i of list) {
let item = i.innerHTML.toLowerCase();
if (item.indexOf(search) == -1) {
i.classList.add("hide");
} else {
i.classList.remove("hide");
if (filter.value.length == 0) {
i.classList.add("hide");
}
}
}
};
});