0

I've been through all of the posts here and none worked so far. I have list of checkboxes with the same class:

<input class="my_checkbox" type="checkbox" value="some_value1">
<input class="my_checkbox" type="checkbox" value="some_value2">
<input class="my_checkbox" type="checkbox" value="some_value3">

I can either toggle them individually or use a toggle button that checks/uncheck all:

$(document).on('click', '#toggle_button', function () {
    if ($(this).prop("checked")) {
        $(".my_checkbox").prop("checked", true);
    } else {
        $(".my_checkbox").prop("checked", false);
    }
});

Now I want to get all the values into an array, and I've tried multiple things and none worked, the array always ends up empty.

I tried:

$('input:checkbox.my_checkbox').each(function () {
     arr.push($(this).val());
});

and:

$('.my_checkbox:checkbox:checked').map(function() {
     arr.push($(this).val());
}).get();

And some more, but nothing seem to work

pileup
  • 1
  • 2
  • 18
  • 45
  • `map()` is the correct function to use but your syntax for it is wrong. Check the question I marked as a duplicate. – Rory McCrossan May 23 '22 at 11:02
  • Also note that the `if` statement in the first example can be reduced to just: `$(".my_checkbox").prop("checked", this.checked);` – Rory McCrossan May 23 '22 at 11:03
  • thank you! I reduced it as you said and it works! however, the solution still returns an empty array, I did exactly this: `var checkedValues = $('.my_checkbox:checked').map(function() { return this.value; }).get(); console.log(checkedValues);` and it's still empty :/ – pileup May 23 '22 at 11:08
  • I'm unable to replicate that behaviour - the code works fine: https://jsfiddle.net/c3f0yqLs/ – Rory McCrossan May 23 '22 at 11:11
  • 1
    Ok wow that is weird, I am going to have to see why, since there aren't typos and the shortened code you suggested also works for me, just the mapping part not. I just wonder where else can it be. Will look now into this. thank you – pileup May 23 '22 at 11:14
  • @RoryMcCrossan I've been through the html construct and JS again, I've even copied my values to your fiddle and there it worked, however in my case it keep returning empty arrays. In my case the inputs are not siblings, they are inside a table ``, but I'm not sure that's supposed to affect anything. So I'm pretty lost. I've never had this type of problem where it works everywhere and not on my code even though it looks identical and other things do work. Do you have any idea what else could cause that? – pileup May 23 '22 at 11:32

0 Answers0