The code worked a few months ago and recently stopped working
It’s for when I text some word and it can auto search the item of list
I have been trying code from a lesson but it still doesn’t work
This is my code
function search() {
let search = document.querySelector('#search');
let li = document.querySelectorAll('li');
for (let data of li) {
console.log(data.textContent.indexOf(search))
if (data.textContent.indexOf(search) > -1) {
data.style.display = '';
} else {
data.style.display = 'none'
}
}
}
<input type="text" id="search" onkeyup="search()">
<ul id="phone">
<li>iPhone 12</li>
<li>iPhone 12 Pro</li>
<li>iPhone 12 Pro Max</li>
<li>iPhone 12 Mini</li>
<li>iPad Air</li>
<li>iPad Pro</li>
<li>iMac</li>
<li>Mac book Air</li>
<li>Mac book Pro</li>
<li>Mac Pro</li>
<li>Test</li>
</ul>
>Solution :
Use the .value
Here is a shorter and improved script:
const lis = document.querySelectorAll('#phone li');
document.getElementById('search').addEventListener('input', function() {
const val = this.value.trim().toLowerCase(); // remove the two .toLowerCase() if you want to be case sensitive
lis.forEach(li => li.hidden = search != "" && !li.textContent.toLowerCase().includes(val));
})
<input type="text" id="search" autocomplete="off">
<ul id="phone">
<li>iPhone 12</li>
<li>iPhone 12 Pro</li>
<li>iPhone 12 Pro Max</li>
<li>iPhone 12 Mini</li>
<li>iPad Air</li>
<li>iPad Pro</li>
<li>iMac</li>
<li>Mac book Air</li>
<li>Mac book Pro</li>
<li>Mac Pro</li>
<li>Test</li>
</ul>