Jquery how to get all selected checkboxes and add them to an 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); }) }) 

I am trying to do the following:

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

When I exit the code now, I get the result as follows:

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

Any help would be greatly appreciated.

Regards, Zoreli

+4
source share
2 answers

You need to use this instead of 'input:checked' inside the .each() function to refer to the current element in the set being checked. If you reuse the selector, you get the set again, and then only get the attributes from the first element in the set.

 $('input:checked').each(function() { names.push($(this).attr("name") + this.id); }); 
+12
source

Change your html to

 <input type="checkbox" name="fruits[]" id="1" class="box">Banana<br /><br /> <input type="checkbox" name="fruits[]" id="2" class="box">Cherry<br /><br /> <input type="checkbox" name="fruits[]" id="3" class="box">Strawberry<br /><br /> <input type="checkbox" name="fruits[]" id="4" class="box">Orange<br /><br /> <input type="checkbox" name="fruits[]" id="5" class="box">Peach<br /><br /> <input type="button" id="groupdelete" value="clickme"><br /> 

And now look at jQuery / Javascript

 $(document).ready(function(){ $('#groupdelete').click(function() { var marked = new Array(); var k = 0; $('input:checked').each(function(index,value) { marked[k] = value; k++; }); alert(marked[0].id); }); }); 

alert just gives you a demo by accessing directly by array index.

+1
source

Source: https://habr.com/ru/post/1401205/


All Articles