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
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);
4 Comments
JPickup
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()); ??Avaq
I'll edit my answer to answer your question more specificly, one moment.
JPickup
also is this more efficient than using .each or just preferred as it is less code?
Avaq
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.
var list = '';
$("[name=ap[]]").is("checked").each(function(){
list += $(this).val() + ',';
});
1 Comment
Anders Arpi
+1 for simplicity, but needs a fence-post fix imo, this will leave a trailing comma
var csv="";
$('input:checkbox[name="ap[]"]:checked').each(function(index) {
if(csv !="" ) csv+=",";
csv+=$(this).val();
});