1

I have multiple checkboxes with name=ap[] and want to use jquery to convert the checked checkbox values into comma separated values so i can then parse as a query string. How would i go about this? .serialize() makes the string over complicated

3 Answers 3

6

jQuery.fn.map itterates over a jQuery set, and returns a new array (inside a jQuery wrapper) which contains nodes equal to the return value of each itterarion. You can then get that array by calling jQuery.fn.get, then use that array for anything you want:

$(':checkbox:checked').map(function(){
  return $(this).val(); // value will be in the returned array
})
.get() // extract the new array from the jQuery object
.join(','); //do anything you want with the array

In your case this can be applied as such:

var list = $(':checkbox[name="ap[]"]:checked').map(function(){
  return $(this).val();
}).get().join(',');

alert(list);
Sign up to request clarification or add additional context in comments.

4 Comments

thanks @avaq I looked at .map but didn't quite understand it fully. so how would i access/alert the csv? alert($(:checkbox:checked).get()); ??
I'll edit my answer to answer your question more specificly, one moment.
also is this more efficient than using .each or just preferred as it is less code?
It does the same as each(), as in; it itterates over a jQuery element set. The difference is that each() is meant for any itteration logic and map() is meant for stuff like your question. I don't know about the performance but I'm guessing it won't make much of a difference. It has the advantage of not having to do an if() check on every itteration, but the performance impact that jQuery adds by wrapping the returned array in a jQuery object.
1
var list = '';
$("[name=ap[]]").is("checked").each(function(){
   list += $(this).val() + ',';
});

1 Comment

+1 for simplicity, but needs a fence-post fix imo, this will leave a trailing comma
0
var csv="";
$('input:checkbox[name="ap[]"]:checked').each(function(index) { 

if(csv !="" ) csv+=",";

csv+=$(this).val();

});

2 Comments

Great thank you :)Just for future reference what do you put the 'index' in there for?
It's the index of the element 0 the first one , two the third one , lets say you need to do something with the third element , you can achieve that using its index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.