return an obj of checkbox values

Go To


I'm trying to get an object of checkbox names and values. Suppose I have this form:

<input type="checkbox" name="email" />
<input type="checkbox" name="name" />
<input type="checkbox" name="hi" />

And Assuming that the first and third are checked, I want this obj:

{ email: 1, name: 0, hi: 1 }

Here's what I tried:

$(':checkbox').map(function() { return + '=' + (this.checked ? 1 : 0) } }).get();

And that gives me:

['email=1', 'name=0', 'hi=1']

But I don't know what do to from here.

Am I going about this wrong?

2012-04-03 22:14
by qwertymk


According to the .map() method doco, .map() returns "a jQuery-wrapped array". Given that you want an object you can instead do something like this:

var checkboxes = {};
$(':checkbox').each(function() {
    checkboxes[] = this.checked ? 1 : 0;

Noting that if you have checkboxes with the same name (which is valid as far as html forms go) then your object will only keep the value of the last checkbox for each name.

2012-04-03 22:25
by nnnnnn
Upvoted for a solution minus my chiding. : - zetlen 2012-04-03 22:36


You can try setting the properties using the associative array syntax: ob["property"] = ...

See this working fiddle:

2012-04-03 22:24
by Tuan


Yeah, you're going about this pretty wrong. From your use of '=' it looks like you expect the function to return JavaScript code that is then run using eval. That's not the way JavaScript operates. Since you're concatenating with a string and a number, JavaScript does its implicit type coercion and returns a string from the function, so you get an array of strings.

The .map() function will always return an array; for miscellaneous operations that don't return an array, you should use the generic .each() iterator.

Here is a quick plugin that does what you want.

$.fn.serializeCheckboxes = function() {

    var ret = {};
    this.each(function(ix,elm) {
        ret[] = elm.checked ? 1 : 0;
    return ret;
2012-04-03 22:27
by zetlen


Try this:

$('input[type="checkbox"]').each(function() {
        var name = $(this).attr('name');
        obj[name] = $(this).is(':checked') ? 1 : 0;

2012-04-03 22:28
by Adam Merrifield
Note that you can make this both more efficient and easier to read if you use and this.checked rather than creating a new jQuery object (twice!) with $(this) - nnnnnn 2012-04-03 22:34