Add Event Listener to checkboxes when selected all at once

Viewed 185

I want to add event listener to all checkboxes, which are selected with span element "select all" --> see example bellow..

This code (i found it on other question on stackoverflow) works only if a checkbox is manually selected:

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

..but not when i click on the "select all"

Example on JSFiddle:

https://jsfiddle.net/f3n9vxzk/3/

Furthermore i would like to display selected checkboxes values on the right side of a page, for example:

If i choose TABLE2 under HR->New objects->Table, i would like to have (on the right side of a page) something similar to that on the left side, but only those values, which are checked..

..something like this:

enter image description here

So my question: is it possible to get parent value of each element in a tree, based on my structure? If yes, i would be very gratefull for any help or just hint (if i'm doing something wrong..).

Thank you!

1 Answers

Code working with both manually select and click on the "select all"

let checkboxes = $("input[type='checkbox']");
let enabledSettings = [];

// function to show selected checkboxes
function checkbox_fun() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
}

$('.resultObjectsNew').on('click', 'span.selectAllNewObj', function(){
        var checked = $(this).parent().next().find('input').prop('checked');
        $(this).parent().next().find('input').prop('checked', !checked);
        checkbox_fun(); // function call
    });
    

// Attach a change event handler to the checkboxes.

checkboxes.change(function() {
  checkbox_fun(); // function call
});

Copy above code to below JSFiddle and successfully run code:

https://jsfiddle.net/f3n9vxzk/3/

Related