Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - Add Event Listener to checkboxes when selected all at once

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!

question from:https://stackoverflow.com/questions/65906480/add-event-listener-to-checkboxes-when-selected-all-at-once

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...