7

I have a checkboxlist control and would like to get all the checkbox values that are checked concatenated into a string separated by '-'. Is there any functions for this? Ex:

$('#checkboxes input[type=checkbox]:checked').concat('-');
BenMorel
  • 34,448
  • 50
  • 182
  • 322
user666423
  • 229
  • 3
  • 14

4 Answers4

13

I think your best bet is

$('#checkboxes input[type=checkbox]:checked').map(function() {
  return $(this).val();
}).get().join('-');

Basically, you're applying a function to each item that returns its value. Then you assemble the result into a string.

Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
5

Check out this previous post. Perhaps using the map() function will work for you.

$('#checkboxes input[type=checkbox]:checked').map(function() {
  return $(this).val();
}).get().join('-');
Community
  • 1
  • 1
Dutchie432
  • 28,798
  • 20
  • 92
  • 109
  • Wow. I thought I was ahead of the curve on this one. – Dutchie432 May 04 '11 at 17:23
  • 1
    The fact all three answers are identical to the answer quoted here, down to exact formatting, means I upvoted this one, as it quoted the source. – Orbling May 04 '11 at 17:24
  • Actually, the real source is the example on the jQuery documentation page for map(); I copied that and modified it. (http://api.jquery.com/map/) – Jacob Mattison May 04 '11 at 17:33
3

I think you want to look at jQuery's .map() functionality (not tested):

$('#checkboxes input[type=checkbox]:checked').map(function() {
  return $(this).attr('value');
}).get().join('-');
Daff
  • 43,734
  • 9
  • 106
  • 120
0

That kind of depends on what you are trying to do. For example -

var list = ''
$('#checkboxes input[type=checkbox]:checked').each(function(){
    list += $(this).val() + '-'
});

Would give you a list with dash separated values but if you are looking to do this for form processing/submission, check into .serialize()

HurnsMobile
  • 4,341
  • 3
  • 27
  • 39
  • 1
    Actually, this would give you a list of dash separated values with an extra blank item at the end. like `item1-item2-item3-` – Dutchie432 May 04 '11 at 17:29