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('-');

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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('-');

3 Comments

Wow. I thought I was ahead of the curve on this one.
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.
Actually, the real source is the example on the jQuery documentation page for map(); I copied that and modified it. (api.jquery.com/map)
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('-');

Comments

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()

1 Comment

Actually, this would give you a list of dash separated values with an extra blank item at the end. like item1-item2-item3-

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.