vendredi 15 février 2019

Can't apply checkbox properties to for loop

Alright so I hope Im just missing something easy. Basically I am making a todo list where I want to have a checkbox appear with each list item (this works). When users click on the checkbox, the textDecoration = "line-through" is supposed to go through the listItem class. Meaning a line goes through the todo task the person creates. Here is the code I am mainly working with:

function show() {
var todos = get_todos();

var html = '<ul>';
for(var i=0; i < todos.length; i++) {
    html += '<span><li class="listItem" style="float:left;">' + todos[i] + '</li><input class="checkBox" type="checkbox">' + '<button class="remove" id="' + i  + '"><i class="fa fa-trash" aria-hidden="true"></i></button></span><br/>';
};
html += '</ul>';

document.getElementById('todos').innerHTML = html;

var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', remove);
};

////////////////////////////////////
//Everything above here works. Below is the checkbox issue

var checkBox = document.getElementsByClassName("checkBox");
var listItem = document.getElementsByClassName("listItem");

for (var i=0; i < checkBox.length; i++) {
    if (checkBox.checked == true){
        listItem.style.textDecoration = "line-through";
    }else {
        listItem.style.textDecoration = "none";
    }
};}

Where I'm at now is if I create an onClick function in the original checkbox, I can use that if/else statement and it kind of works. It will not work if I set the checkBox/listItems variables using document.getElementsByClassName but it will work if I use document.getElementById. The problem is that it only works on the first task that the user creates and none of the other ones created after. Im assuming that is either because Ids only work for one element (unlike a class that works for multiple) or because its not cycling through a for loop like it is in the code above.

TL/DR Basically when I run the code above I keep getting "Uncaught TypeError: Cannot set property 'textDecoration' of undefined at show (todo.js:57) at todo.js:75".

I dont get this error when I make a separate function for the checkbox and use elementbyid instead of elementsbyclass (changing the id/class of the html section above too)

I really want to get those line-through effects working on all tasks, not just the first one. Any ideas are greatly appreciated. Thanks everyone!

Aucun commentaire:

Enregistrer un commentaire