lundi 1 juillet 2019

How to add/remove class from a parent List-item(li) when their child checkbox is changed in javascript?

I am building a simple Todo app in Javascript but I got stuck trying to add/remove a class to a List-item(li) that is the parent of a checkbox.

By default a list-item (Todo) checkbox is unchecked (with no class added). Whenever a user check a todo checkbox, a class is added, and the todo text gets a line through.

I managed to make it work but nothing happens.

HTML CODE:

<p class="lead text-center">Welcome to my todoList applications</p>
    <div class="row">
       <form id="form" class="col-lg-6 col-8 mx-auto">
    <div class="input-group">
        <input type="text" id="input" class="form-control" ><span>
        <button id="btn" type="button" class="btn btn-primary">Submit</button></span>
    </div>               
       </form>
      </div>            
  <div class="row">             
    <ul id="list" class="list col-lg-6 col-8 mx-auto">
  <!-- <li>this is a todo item <input type="checkbox" class="checkbox"></li>
        <li>this is a todo item <input type="checkbox" class="checkbox"></li> -->
    </ul>
   </div>
<div class="row">
<button id="btnClr" type="button" class="btn btn-primary mx-auto btnHide">Clear All Todos</button>
</div>


JAVASCRIPT CODE:

// ADD ITEM, REMOVE ITEM - FUNCIONALITY 
const btn = document.getElementById('btn');
const ulList = document.getElementById('list');

// Button event listener with adding li elemnts with input value
btn.addEventListener('click', function(){
    var input = document.getElementById('input').value; // Capture input value
    var newItem = document.createElement("LI");     // Create a <li> node
    newItem.innerHTML = input + '<input type="checkbox" class="checkboxes" ><p class="delet">x</p>';  // Add content to li element for todo.                   
    ulList.insertBefore(newItem, ulList.childNodes[0]);  // Insert <li> before the first child of <ul>
    // input = ' ';  // Reset input value to empty field

    // Remove item funcionality 
    newItem.childNodes[2].onclick = function() {this.parentNode.remove(this);}
})

// ********** IMPORTANTO CODE BELOW ***********************
// MARK DONE TODO  - FUNCIONALITY 

var checkBox = document.getElementsByClassName('checkboxes');

for (var i = 0; i < checkBox; i++) { 
    checkBox[i].addEventListener('change', function() {
        if(this.checked) {
            // Checkbox is checked..
            this.parentNode.classList.add("line-through");
        } else {
            // Checkbox is not checked..
            this.parentNode.classList.remove("line-through");
        }
    }); 
}

CSS CODE (Line through):

.line-through {
    text-decoration: line-through;
  }

I would appreciate any help. Thanks in advance everyone! :)




Aucun commentaire:

Enregistrer un commentaire