Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery checkboxes, how to get all selected checkboxes and add them to array?

Hi I have the following page:

<input type="checkbox"  name="fruit1" id="1"  class="box">Banana<br /><br />
<input type="checkbox"  name="fruit2" id="2"  class="box">Cherry<br /><br />
<input type="checkbox"  name="fruit3" id="3"  class="box">Strawberry<br /><br />
<input type="checkbox"  name="fruit4" id="4"  class="box">Orange<br /><br />
<input type="checkbox"  name="fruit5" id="5"  class="box">Peach<br /><br />
<input type="button" id="groupdelete" value="clickme"><br />

 $(document).ready(function(){

$('#groupdelete').on('click', function(){
  var names = [];
   $('input:checked').each(function() {

       names.push($('input:checked').attr("name") + $('input:checked').attr('id'));

 });
   console.log(names); 
})

})

What I am trying to do is the following:

To add the checked checkboxes in the array. And after that, I would like to be able to pass the value in php variable.

When I excecute the code now, I am getting result like this:

["fruit22", "fruit22", "fruit22"]

Any help will be deeply appreciated.

Regards, Zoreli

like image 447
Zoran Avatar asked Dec 12 '22 04:12

Zoran


1 Answers

You need to use this rather than 'input:checked' inside the .each() function to refer to the current element in the set being examined. If you re-use the selector you're getting the set again, then only ever getting the attributes from the first element in the set.

$('input:checked').each(function() {
    names.push($(this).attr("name") + this.id);
});
like image 135
Anthony Grist Avatar answered Mar 30 '23 01:03

Anthony Grist