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")
}
});
}
});
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")
}
});
You can do other way around like this
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")
}
});
}
})(); // <--added this
You could simply remove your anonymous function
var checkb = document.getElementById("checkbox1"); checkbFunc(checkb); function checkbFunc(checkb) { checkb.addEventListener("click", function(e) { if( checkb.checked ) { alert("i am checked"); } else { alert("i am not checked") } }); }
<input type="checkbox" id="checkbox1"/>
Or, better, use JQuery document.ready block.
your code is not working because the main anonymous functions is not executed.
The code below should work for you.
var checkb = document.getElementById("checkbox1");
(function() {
checkbFunc(checkb);
function checkbFunc(checkb) {
console.log(checkb);
checkb.addEventListener("click", function(e) {
if( checkb.checked ) {
alert("i am checked");
} else {
alert("i am not checked")
}
});
}
}() // Add these round braces );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.