Dan Knights
Dan Knights

Reputation: 8378

Variable not updating on change - jQuery

I have an array of checkboxes, when one is clicked, I want to store a new array of which boxes are and aren't checked. However, when I console.log() the new array, it's still filled with all of them regardless of what state they're in.

Anyone know why?

Code:

// checkboxes
  const blue = $('#blue');
  const green = $('#green');
  const white = $('#white');
  const red = $('#red');
  const black = $('#black');
  const colourless = $('#colourless');
  const multicoloured = $('#multicoloured');

// store checkbox values in an array;
  let colourCheckbox = [
    blue,
    green,
    white,
    red,
    black,
    colourless,
    multicoloured
  ];

// loop through array to find out which ones are checked
  let checkedCheckboxes = $('.colour-checkbox').change(() => {
    colourCheckbox.forEach(element => {
      if ($(element).is(':checked')) {
        return element;
      }
    });
  });

Upvotes: 1

Views: 165

Answers (3)

Carsten Massmann
Carsten Massmann

Reputation: 28246

You are making life unnecessarily difficult for yourself. If you want to get a collection of checked DOM elements each time one the checkboxes has been clicked on you could do:

let allBtns=$('#blue,#green,#white,#red,#black'
+',#colourless,#multicoloured');
let chkd;
allBtns.click(e=>chkd=allBtns.filter(':checked'))

This will get you a jQuery selection (chkd) with all checked checkboxes in it. These lines contain all you need to do.

If you want an Array of plain DOM elements instead of the jQuery selection you can apply .toArray() on it:

let DOMarr=chkd.toArray()

Upvotes: 1

Dan Knights
Dan Knights

Reputation: 8378

Appreciate the answers but they didn't work for some reason.

Did some fiddling about and solved it this way:

  let colourCheckbox = [
    blue,
    green,
    white,
    red,
    black,
    colourless,
    multicoloured
  ];

  let checkedCheckboxes = [];

  $('.colour-checkbox').change(() => {
    checkedCheckboxes.length = 0;
    colourCheckbox.forEach(element => {
      if ($(element).is(':checked')) {
        checkedCheckboxes.push(element);
      }
    });
  });

Firstly, initialized an empty array, then on change, looped through the colourCheckbox array and pushed the :checked boxes to the empty array. Lastly, used checkedCheckboxes.length = 0; to clear the previous looped results from the checkedCheckboxes array.

Upvotes: 0

Barmar
Barmar

Reputation: 782785

.change() doesn't return an array, it returns the jQuery collection that you bind the handler to.

You need to assign the variable inside the handler function. And you need to use .filter().

let checkedCheckboxes;
$('.colour-checkbox').change(function() {
    checkCheckboxes = colourCheckboxes.filter(el => el.is(':checked')).get();
});

Upvotes: 2

Related Questions