0

After following answers like this one, I'm trying to append data to a string using:

<input type='checkbox' name='a' />A
<input type='checkbox' name='b' checked='checked'/>B
<input type='checkbox' name='c' />C

var attr_str = $('input').serializeArray();
attr_str.push({q:'hello',p:'world'});

But it returns [object Object],[object Object]. What am I missing?

JSFIDDLE

Community
  • 1
  • 1
greener
  • 4,989
  • 13
  • 52
  • 93

2 Answers2

0

The serializeArray returns an array of objects, each contains the properties name and value.

Ex

[{"name": "x", "value": "y"}, {"name": "a", "value": "b"}, ...]

That is why it is printing [Object, Object].

You can use JSON.stringify(attr_str) to print the stringified values if you want. But JSON.stringify is not natively supported in old browsers, so you may have to include a compatibility library like JOSN2

Demo: Fiddle.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

I'm not sure what you're trying to accomplish but only the input which is checked is going to be included by serializeArray(). You can read more about it here.

But your array is being returned as an object as it should. To see the layout of the JSON of this object you could try JSON.stringify(attr_str).

var attr_str = $('input').serializeArray();

attr_str.push({q:'hello',p:'world'});

$('body').append('<br><br>string='+JSON.stringify(attr_str));

This will show that you are appending an object into yourattr_str array but only input 'b' is included because it is the only one that is checked. string=[{"name":"b","value":"on"}{"q":"hello","p":"world"}] To access this object you would simply use attr_str[0] then for a property of that object use attr_str[0].name. Which would print b.

dnapierata
  • 1,153
  • 1
  • 16
  • 28