menu

Questions & Answers

Is there a way to click on a checkbox to make a list item active?

I want to check a checkbox and a class will be added to a list item that will reduce the opacity and also line-through the list item to show completion of task.

This is what I did but it is not working.

var btn = document.querySelector('.btn') 
var inputValue = document.querySelector('input');
var ulContainer = document.querySelector('.ul-container');
var input = document.querySelector('.check-input');

console.log(input);

var li = document.createElement('li'); // EVENTLISTENERS

btn.addEventListener('click', generateToDo);

input.addEventListener('click', complete); // FUNCTION 

function generateToDo() {
  var div = document.createElement('div');
  div.classList.add('div-1');
  var ul = document.createElement('ul');
  li = document.createElement('li');
  var z = inputValue.value;
  li.textContent = z;
  ul.appendChild(li);
  div.appendChild(ul);
  var input = document.createElement('input');
  input.type = 'checkbox';
  input.classList.add('check-input');
  div.appendChild(input);
  var dleBtn = document.createElement('button');
  dleBtn.innerHTML = '';
  dleBtn.classList.add('btn-trash');
  div.appendChild(dleBtn);
  ulContainer.appendChild(div);
}
<div class="main-container">
  <div class="ul-container center"></div>
</div>`

Answers(1) :

I think you want to do something like this:

let list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);
* {
  box-sizing: border-box;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;

  user-select: none;
}


ul li.checked {
  opacity: 0.3;
  text-decoration: line-through;
}
<ul id="myUL">
  <li>Todo1</li>
  <li class="checked">Todo2</li>
  <li>Todo3</li>
</ul>

This probably isn't the best solution, but good enough for a simple todo app.

A complete todo app can be found here.

Comments:
2023-01-20 23:10:11
the thing is I want to create a div, li, delete btn and the checkbox when a user click on a add button. so if a user check the checkbox a class will be added to the li is which the todo to show completion of the task.