return an obj of checkbox values

Go To StackoverFlow.com

0

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

<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.name + '=' + (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


4

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.name] = 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


1

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

See this working fiddle: http://jsfiddle.net/tuando/JwYFz/

2012-04-03 22:24
by Tuan


1

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 this.name 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.name] = elm.checked ? 1 : 0;
    });
    return ret;
}
2012-04-03 22:27
by zetlen


1

Try this:

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

http://jsfiddle.net/T7fja/1/

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