简体   繁体   中英

Trying to filter an array but not getting desired output

I have a filtertask input, so whenever the user types something it should only shows the tasks that match the typed task

The filtering is working fine, but after I delete the text typed, the list of tasks does not appear again

here list-item is the class of li elements

If there are 'singh' and 'sharma' in the tasklist, and I type 'm' to filter, it shows 'sharma'. but when I clear the filtertask input, only 'sharma' shows up instead of 'singh' and 'sharma'

 filter.addEventListener('keyup', filTask); function filTask(e) { const text = e.target.value.toLowerCase(); if (text !== '') { document.querySelectorAll('.list-item').forEach(function(task) { const item = task.firstChild.textContent; if (item.toLowerCase().indexOf(text) != -1) { task.style.display = 'block'; } else { task.style.display = 'none'; } }); } } 

You simply need else part here,

if (text !== '') {
    document.querySelectorAll('.list-item').forEach(function(task) {
        const item = task.firstChild.textContent;
        if (item.toLowerCase().indexOf(text) != -1) {
            task.style.display = 'block';
        } else {
            task.style.display = 'none';
        }
    });
} else {
    document.querySelectorAll('.list-item').forEach(function(task) {
        task.style.display = 'block';
    });
}

You have missed the else condition. when the text is empty you need to set the display:block to all the elements.

 var filter = document.getElementById('search'); filter.addEventListener('keyup', filTask); function filTask(e) { const text = e.target.value.toLowerCase(); if (text !== '') { document.querySelectorAll('.list-item').forEach(function(task) { const item = task.firstChild.textContent; if (item.toLowerCase().indexOf(text) != -1) { task.style.display = 'list-item'; } else { task.style.display = 'none'; } }); } else { document.querySelectorAll('.list-item').forEach(function(task) { task.style.display = 'list-item'; }); } } 
 <input type="text" id="search"/> <ul> <li class="list-item">sharma</li> <li class="list-item">singh</li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM