Checkbox Check Event Listener

前端 未结 3 1980
深忆病人
深忆病人 2020-11-28 03:58

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 wi

3条回答
  •  醉酒成梦
    2020-11-28 04:23

    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..");
      }
    });

    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..")
      }
    });
    
    
    

    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)
      })
    });
    
    
    

    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);
    });
    
    
    
    

提交回复
热议问题