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")
}
});
}
});
(function() { ... });never executes the anonymous function. But if you change it to(function() { ... })();then it does and your fiddle works.