Someone33
Someone33

Reputation: 568

Looping through selected checkboxes jQuery

I'm trying to get the values of all selected checkboxes with the following code to insert them in a textarea.

 $('input[name="user"]:checked').each(function(){
     parent.setSelectedGroup($(this).val()+ "\n");
  });

but i always get only one value.

How to write the code in a correct way to get the value of ALL selected checkboxes?

Thanks ahead!

EDIT

1) "parent" because the checkboxes are in a fancybox.iframe.

2) setSelectedGroup in the parent window is

function setSelectedGroup(groupText){
$('#users').val(groupText);

Upvotes: 0

Views: 2202

Answers (1)

George Mauer
George Mauer

Reputation: 122052

You are getting all the values, simply on each loop through the collection you're passing a new value to setSelectedGroup. I assume that method replaces content rather than appending so you are simply not seeing it happen because its too fast.

parent.setSelectedGroup(
  //select elements as a jquery matching set
  $('[name="user"]:checked')                
    //get the value of each one and return as an array wrapped in jquery
    //the signature of `.map` is callback( (index in the matching set), item)        
    .map(function(idx, el){ return $(el).val() })
    //We're done with jquery, we just want a simple array so remove the jquery wrapper
    .toArray()
    //so that we can join all the elements in the array around a new line
    .join('\n')
);

should do it.

A few other notes:

  • There's no reason to specify an input selector and a name attribute, usually name attributes are only used with the input/select/textarea series of elements.
  • I would also avoid writing to the DOM inside of a loop. Besides it being better technique to modify state fewer times, it tends to be worse for performance as the browser will have to do layout calculations on each pass through the loop.
  • I strongly recommend almost always selecting the parent element for the parts of the page that you're concerned with. And passing it through as the context parameter for jquery selectors. This will help you scope your html changes and not accidentally modify things in other parts of the page.

Upvotes: 3

Related Questions