Description
i have multiple checkbox and want handle all checkbox click event in single handler function
and want to know which is checked.i tried below code and not working
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#Checkbox1').addEventListener('change', changeHandler("Checkbox1"));
document.querySelector('#Checkbox2').addEventListener('change', changeHandler("Checkbox2"));
document.querySelector('#Checkbox3').addEventListener('change', changeHandler("Checkbox3"));
document.querySelector('#Checkbox4').addEventListener('change', changeHandler("Checkbox4"));
document.querySelector('#Checkbox5').addEventListener('change', changeHandler("Checkbox5"));
});
function changeHandler(checkboxs) {
//Do Something...maybe another function showAlert(), for instance
if (checkboxs.checked) {
console.log("Checkbox checked");
}
else {
console.log("Checkbox unchecked");
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
<body>
<div>
Checkbox1: <input type="checkbox" id="Checkbox1">
</div>
<div>
Checkbox2: <input type="checkbox" id="Checkbox2">
</div>
<div>
Checkbox3: <input type="checkbox" id="Checkbox3">
</div>
<div>
Checkbox4: <input type="checkbox" id="Checkbox4">
</div>
<div>
Checkbox5: <input type="checkbox" id="Checkbox5">
</div>
</body>
</html>