Stophface Stophface - 2 months ago 19
CSS Question

Adding eventListener to checkbox

Can I add an

eventListener
in
JavaScript
to a checkbox or do I have to use the attribute in html
onclick = someFunc()
to trigger a function.
I set a up a fiddle where I tried to add an
eventListener
, but that does not give me the expected output.

var checkb = document.getElementById("checkbox1");

(function() {

checkbFunc(checkb);

function checkbFunc(checkb) {
checkb.addEventListener("click", function(e) {
if (checkb.checked) {
alert("i am checked");

} else {
alert("i am not checked")
}
});
}
});

Answer

Yes, you can. Just unwrap your code from all the functions, and use the change event instead, and it should work fine

var checkb = document.getElementById("checkbox1");

checkb.addEventListener("change", function(e) {
    if (this.checked) {
        alert("i am checked");
    } else {
        alert("i am not checked")
    }
});

FIDDLE