Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my code textContent.indexOf can't compare input value

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading