0

I am a begginer in this field, and still learning. I tried to do a 'Todo' list, and have the following code written (used JQuery). I can add items to the list (all items have 2 buttons of its own)

I can not make the list item buttons to work. One is a checkbox type, witch should change the color of the text of that item. The second button should delete the item from the list (with the buttons for that item too)

Could somone help me to make this code work?

$(document).ready(function(){
$('#add').click(() => {
    let listaInput = $('#szovegDoboz').val()
    $("ul").append(
        `<li>
            <span>
                <p class = "listaElem">${listaInput}</p>
                <p>
                    <button class = "myButton"><img src = "./content/del.svg" width = "20px" height = "20px"></button>
                    <input type = "checkbox"/>
                </p>
            </span>
        </li>`)
})
$('input[type="checkbox"]').on('change', 'li', function() {
    if (this.checked) {
        $(this).css('color', 'gainsboro')
    }
    else {
        $(this).css('color', 'dimgray')
    }
})
$('.mybutton').on('click', 'li', function() {
    $(this).remove('li')
})

})

Wookie
  • 43
  • 5
  • 1
    Try with `$('.mybutton').on('click', function() {$(this).closest("li").remove()})` – Carsten Løvbo Andersen Aug 10 '21 at 06:24
  • Your event delegation is round the wrong way: `$('input[type="checkbox"]').on('change', 'li'` (and the `.mybutton` one highlighted in the comment above). It should be: `$(static_selector).on("event", child_selector,...` so would be `$('li').on('change', 'input[type="checkbox"]'` - however `li` would also be dynamic, so you want `$('ul').on('change', 'input[type="checkbox"]'` - same for 2nd event: `$("ul").on("click", ".mybutton", function() { $(this).closest("li").remove() })` – freedomn-m Aug 10 '21 at 07:55
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Aug 10 '21 at 07:55
  • Thank you for all the help, it is working now :) – Wookie Aug 10 '21 at 09:09

0 Answers0