Checkbox Check Event Listener
Solution 1
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Single checkbox
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
<input type="checkbox" name="checkbox" />
Single checkbox with jQuery
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
Multiple checkboxes
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
Multiple checkboxes with jQuery
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
Solution 2
Since I don't see the jQuery
tag in the OP, here is a javascript only option :
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE
Solution 3
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
Related videos on Youtube
Oliver Kucharzewski
Follower of Christ & Lover of all things programming
Updated on July 08, 2022Comments
-
Oliver Kucharzewski almost 2 years
Recently I have been working with the Chrome Plugin API and I am looking to develop a plugin which will make life easier for me for managing a website.
Now what I wish to do is to fire an event when a certain checkbox is checked. As this website does not belong to me I cannot change the code therefore I am using the Chrome API. One of the main problems is that rather than there being an ID, there is a Name. I was wondering if I could fire the function once the certain checkbox with the 'name' is checked.
-
thordarson about 7 yearsYou're right, and I upvoted your answer way back when. I've added a jQuery free option using the querySelector method.
-
JFK about 7 years
Using the jQuery-like querySelector
...mmm, is not a "jQuery-like" (feel tempted to downvote) -
thordarson about 7 yearsWhat I meant is that jQuery made the use of query selectors widespread in Javascript. Before they came around, selecting and finding elements was a hassle.
-
kuzey beytar over 6 yearsalways use
addEventListener
instead of direct event likeonchange
for further compatibility. -
thordarson over 6 years@dino onchange is supported by all browsers and there is absolutely no difference between on[event] and addEventListener other than use cases that may or may not fit your specific project. Please tell me in what way my answer deserves a downvote. Does it not answer the question?
-
kuzey beytar over 6 years@thordarson
onchange
doesn't add an event listener. It replaces the existing one. It means you block that object with one event only and it may not good for further plugins or scripts working with the same object. If i have a "Start Chat" button, i would like it to be hooked by other themes, plugins or scripts. -
Linus almost 6 yearsWhy did you add the underscore to the _selector variable?
-
JFK almost 6 years@Linus: no technical reason. I believe at the time of the answer I was working with a customer, where all private variables within a function started with underscores and I guess I unconsciously replied in the same way. It works alike without them jsfiddle.net/13pog9L8 Please note the important thing about using or not underscores in variables is consistency throughout the code (yours or the company you work for)
-
SabU over 5 yearsYou can do: if (event.target.checked){ //do something }else{ //do something }
-
JFK over 5 years@SabU there are thousand ways to do the same thing ;)
-
Crayons about 3 yearsGood answer, except the resulting array is just an array of
on
string values. There's nothing relating that value to an actual option. I would instead, consider something like.map(i => ({ [i.id] : i.value }))
so that you can at least associate the checkbox setting to itsid
or data attribute (i.dataset.myattr
) -
funder7 almost 3 yearsThis is the best answer, value should be determined from the incoming event, not external selectors :-)