Friederike
Friederike

Reputation: 1282

Get checkboxes (with the same name) as array

I have an HTML form that contains a set of checkboxes:

<p><input type="checkbox" name="fruits" value="apple" /> Apple</p>
<p><input type="checkbox" name="fruits" value="banana" /> Banana</p>
<p><input type="checkbox" name="fruits" value="strawberry" /> Strawberry</p>

When I click a button I want to have all the selected checkboxes with the same name in one array.

So, if the user selects Apple and Banana I expect something like this:

{ 'fruits' : [ 'Apple', 'Banana' ] }

I tried to use jQuery's serializeArray() method but the result is not as I expected...

[ { name="fruits",  value="apple"}, { name="fruits",  value="banana"} ]

I've created this jsfiddle with my example code.

I know I could iterate over this array and create the object I want. But my question is:
Is there a clean & simple way (using jQuery or some plugin) to do this?

*Edit: * I'm looking for some kind of generic solution to this problem. I'd like to tell a method the form element and have that method automatically find all data. Just like the jQuery.serializeArray() does.

Upvotes: 2

Views: 7845

Answers (2)

Ram
Ram

Reputation: 144669

You can use map method.

$('#submitBtn').click(function() {
    var obj = {};
    obj.fruits = $('input[name=fruits]:checked').map(function(){
        return this.value;
    }).get();
    console.log(obj);
});

http://jsfiddle.net/62f3X/1/

You can use also create the properties using name properties:

$('#submitBtn').click(function() {
    var obj = {};
    $('input[type=checkbox]:checked').each(function() {
        if (!obj.hasOwnProperty(this.name)) 
            obj[this.name] = [this.value];
        else 
            obj[this.name].push(this.value);
    });
    // console.log(obj);
});

http://jsfiddle.net/62f3X/2/

Upvotes: 2

Darren
Darren

Reputation: 70728

There may be a better way to achieve this but you could do:

var fruits = [];

$('#selectAll').click(function() {
   $('input:checkbox').prop('checked', true);
});

$('#submitBtn').click(function() {
   $("input[name=fruits]:checked").each(function() {
     var fruit = $(this).val();
     fruits.push(fruit);
  });

  console.log(fruits);
});

http://jsfiddle.net/NzeVU/3/

Upvotes: 2

Related Questions