mercredi 13 décembre 2017

addEventListener on programatically created checkbox not working

I've made a function that takes a select multiple input and generate checkboxes based on the options of this select. Then, I want that each checkbox execute some action when clicked. The function is:

const makeCheckboxDropdown = (input) => {
    if (input.type !== "select-multiple") {
        console.error("The input must be an `select multiple` type!")
        return
    }

    input.options[0].selected = false

    const header = document.getElementById('header')
    const outer = document.createElement('div')
    const options = input.options
    for (i = 0; i < options.length; i++) {
        let div = document.createElement('div')
        div.classList.add('checkbox')

        let label = document.createElement('label')

        let cb = document.createElement('input')
        cb.type = "checkbox"
        cb.value = options[i].value
        cb.addEventListener("change", (e) => console.log("clicked"))

        label.appendChild(cb)
        label.innerHTML += options[i].value

        div.appendChild(label)
        outer.appendChild(div)
    }
    header.parentNode.insertBefore(outer, header.nextSibiling)
}

Everything works: the checkbox are generated as intended. Except that, when I click the checkboxes, nothing happens. It should log "clicked" on console, but nothing happens. Strangely, if I add this same EventListener through browser debug console, it works.

What is happening here?




Aucun commentaire:

Enregistrer un commentaire