Filter function not working in a Todo App

i’m a beginner trying to learn JS, I have made this todo app, everything’s working fine but for some reason the filter function won’t work, i tried everything I could think of. Please help.

I had already made this app with materialize and it worked fine.

I already tried to use task.style.display and task.className but it didn’t work.

SITE DEMO
https://codepen.io/salma-py97/pen/mdOdLvo?editors=1010

here’s the HTML:

  <body class="bg-secondary">
      <div class="container">
          <div class="row">
              <div class="col">
                  <div class="col-md-6 mx-auto">
                    <div class="card card-body text-center mt-5">
                        <h2 class="display-5 pb-3">
                            <i class="fas fa-list"></i> &nbsp; Task List
                        </h2>
                        <form id="task-form">
                            <div class="form-group">
                              <input type="text" class="form-control" id="task-input" placeholder="Task" value="">
                            </div>
                            <div class="form-group">
                                <input type="submit" value="Add Task" class="btn btn-dark btn-block">
                            </div>
                        </form>
                        
                        <hr>
                        <h3 class="display-5">Task</h3>
                        <div class="form-group">
                            <input type="text" class="form-control" id="filter-tasks" placeholder="Filter Tasks">
                        </div>
                        <ul class="list-group mb-4" id="task-list"></ul>
                        <div class="form-group">
                            <input type="submit" class="btn btn-large btn-dark mx-auto" id="clear-tasks" value="Clear Tasks">
                        </div>
                    </div>
                  </div>
              </div>
          </div>
      </div>
    

here’s the JS:

// Define UI Variables
const form = document.querySelector('#task-form');
const taskInput = document.querySelector('#task-input');
const filter = document.querySelector('#filter-tasks')
const taskList = document.querySelector("#task-list");
const clearBtn= document.querySelector("#clear-tasks");

// Load All Event Listeners
loadEventListeners();

// Event Listeners
function loadEventListeners(){
    // DOM Event Load
    document.addEventListener('DOMContentLoaded', getTasks);
    // Add Task
    form.addEventListener('submit', addTask);
    // Remove task (Event delegation --> putting the eventlistener on the parent element(ul))
    taskList.addEventListener('click', removeTask);
    // filter Tasks
    filter.addEventListener('keyup', filterTasks);
    // Clear Tasks
    clearBtn.addEventListener('click', clearTasks)
}


// Event Handlers
// Get ALL the Tasks when the DOM Loads
function getTasks(){
    let tasks;
    if (localStorage.getTasks("tasks")===null){
        tasks=[];
    } else {
        tasks=JSON.parse(localStorage.getItem("tasks"));
    }
    tasks.forEach(function(task){
        // Create li element
        const li = document.createElement('li');
        // Add Bootstrap4 class
        li.className = 'list-group-item d-flex justify-content-between'
        // Create TextNode and append to li
        li.appendChild(document.createTextNode(task));
        // Create link element
        const link = document.createElement('a');
        // Add class to link
        link.className='delete-item';
        // Add icon innerHTML
        link.innerHTML = '<i class= "fa fa-remove"></i>';
        // append link to li
        li.appendChild(link);
        // append li to ul
        taskList.appendChild(li);
    })       
}
    

//Add Task
function addTask(e){
    if(taskInput.value === ""){
        alert("Add task");
    } else {
        // Create li element
        const li = document.createElement('li');
        // Add Bootstrap4 class
        li.className = 'list-group-item d-flex justify-content-between'
        // Create TextNode and append to li
        li.appendChild(document.createTextNode(taskInput.value));
        // Create link element
        const link = document.createElement('a');
        // Add class to link
        link.className='delete-item';
        // Add icon innerHTML
        link.innerHTML = '<i class= "fa fa-remove"></i>';
        // append link to li
        li.appendChild(link);
        // append li to ul
        taskList.appendChild(li);
        // store in LocalStorage
        AddTasktoLocalStorage(taskInput.value);
        // clear taskInput
        taskInput.value='';
        // Prevent Default behaviour of forms
        e.preventDefault();
    }        
}

// Add task to LocalStorage
function AddTasktoLocalStorage(task){
    let tasks;
    if (localStorage.getItem("tasks")=== null){
        tasks=[];
    } else {
        tasks= JSON.parse(localStorage.getItem("tasks"));
    }
    tasks.push(task);
    // store the new array
    localStorage.setItem("tasks", JSON.stringify(tasks));
}


// Remove task
function removeTask(e){
    // Event Delegation
    if (e.target.parentElement.classList.contains('delete-item')){
        e.target.parentElement.parentElement.remove();
    }
    // remove from LocalStorage
    removeTaskFromLocalStorage(e.target.parentElement.parentElement);
    
}

function removeTaskFromLocalStorage(taskItem){
    // initialise tasks
    let tasks;
    // check if tasks is stored in LS
    if (localStorage.getItem("tasks")===null){
        // if it is not, set tasks array
        tasks=[];
        // if it is, parse through it
        tasks = JSON.parse(localStorage.getItem("tasks"));
    }
    //loop through the tasks array
    // if a task in the array matches the task we want removed --> remove it
    tasks.forEach(function(task, index){
        // !!!! task is text, taskItem should be text as well
        if(task === taskItem.textContent){
            // remove 1 task starting from its index
            tasks.splice(index,1);
        }
    })
            
    // store new tasks array
    localStorage.setItem("tasks", JSON.stringify(tasks));
}
    
    
// filter Tasks
function filterTasks(e){
    // compare between tasks in the ul and the input in the filter
    const text = e.target.value.toLowerCase();
    // console.log(text);
    document.querySelectorAll('.list-group-item').forEach(function(task){
        // if the filterInput matches a task, show task
        // console.log(task);
        const item = task.firstChild.textContent;
        if(item.toLowerCase().indexOf(text) != -1){
            task.classList.add("d-block");
        // else hide task
        } else {
            task.classList.add("d-none");
        }
    })
}

// Clear Tasks
function clearTasks(e){
    // Clear ul
    taskList.innerHTML="";
    e.preventDefault();
    // Clear LocalStorage
    clearsTasksFromLocalStorage();

}

// Clear LocalStorage
function clearTasksFromLocalStorage(){
    localStorage.clear();
}

29 thoughts on “Filter function not working in a Todo App”

Leave a Comment