Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox Check Event Listener

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.

like image 318
Oliver Kucharzewski Avatar asked Jan 27 '13 03:01

Oliver Kucharzewski


People also ask

Which is event listener for checkbox control?

To add a checkbox check event listener with JavaScript, we can listen for the change event. to add a checkbox. const checkbox = document. querySelector("input[name=checkbox]"); checkbox.

How do I check if a checkbox is checked in an event?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Can you use onChange on checkbox?

Use onChange as Attribute on Checkbox in JavaScript The instance here has a checkbox, and when checked, it will run a function that will depict the change. The keyword this refers to a global object, and the onChange attribute grabs and triggers the Check function. The value.


2 Answers

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>
like image 87
thordarson Avatar answered Oct 12 '22 23:10

thordarson


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

like image 28
JFK Avatar answered Oct 13 '22 01:10

JFK