132

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51

3 Answers3

291

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>
thordarson
  • 5,943
  • 2
  • 17
  • 36
  • 7
    `Using the jQuery-like querySelector` ...mmm, is not a "jQuery-like" (feel tempted to downvote) – JFK Apr 27 '17 at 01:00
  • 5
    What 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. – thordarson Apr 27 '17 at 10:17
  • 4
    always use `addEventListener` instead of direct event like `onchange` for further compatibility. – kuzey beytar Aug 18 '17 at 20:01
  • 3
    @dino onchange is [supported by all browsers](https://developer.mozilla.org/en-US/docs/Web/Events/change#Browser_compatibility) and there is absolutely [no difference between on\[event\] and addEventListener](https://stackoverflow.com/a/6348597/2005939) 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? – thordarson Aug 20 '17 at 16:42
  • 9
    @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. – kuzey beytar Aug 20 '17 at 16:59
  • Good 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 its `id` or data attribute (`i.dataset.myattr`) – Crayons Mar 23 '21 at 14:31
58

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

JFK
  • 40,963
  • 31
  • 133
  • 306
  • You're right, and I upvoted your answer way back when. I've added a jQuery free option using the querySelector method. – thordarson Apr 26 '17 at 22:05
  • Why did you add the underscore to the _selector variable? – Linus Jun 05 '18 at 09:04
  • @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 http://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) – JFK Jun 15 '18 at 04:13
  • 1
    You can do: if (event.target.checked){ //do something }else{ //do something } – SabU Dec 03 '18 at 18:55
  • 1
    @SabU there are thousand ways to do the same thing ;) – JFK Dec 06 '18 at 00:29
37

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
    }

});
Penguin9
  • 481
  • 13
  • 23
SabU
  • 603
  • 6
  • 4
  • 2
    This is the best answer, value should be determined from the incoming event, not external selectors :-) – funder7 Jun 19 '21 at 21:20