Well the other day I was doing some forms and ran into a long list of checkboxes that I needed a list of the values, not a name-value array(so serializeArray() wouldn’t help) so I whipped up a small jQuery plugin to return me simply an array of the values of a selector:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
So to call this mean machine we would do:
var arr = $("input[name='fieldname']:checked").getCheckboxVal()
//would return an array like:
// ['val1', 'val2', 'val3']
And if I needed it as a string I would then just do a join(“,”) on the array that was returned. If there is an easier way please drop a line, although this was pretty darn straight forward.. Hope this helps someone like it did me!
Related posts:


3 Responses
apot
12|Jan|2009there are several form plugins that can help with this, check out jquery’s plugin site.. they’re not quite this light weight, but they have a bunch of useful functions
Ron
08|Sep|2011Thanks! Works for me!
Jarry
19|Jan|2012very elegant way.
thanks for publishing