2

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.

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I like the look of this! But I still have to manually set obj.fruits. Is it possible just to pass the form element and have a method determine the name and values by itself?
2

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/

1 Comment

I prefer this solution to the accepted one. Could even trim a line and just push $(this).val() or $(this).value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.