views:

69

answers:

4

Hi

I am trying to insert an key/value pair into a serializeArray(from jquery).

So I have something like

var form = $('#form');
var sendFormData = form.serializeArray();
sendFormData.push({ "name": "Name", "value": "test"});

In firefox this works yet in IE 8 I get

Line: 51 Error: Object doesn't support this property or method

So it seems to be pointing to this line. So does ie 8 not support push if so what is a way I can add a key/value pair that will work in all browsers(the 5 mains ones firefox, ie8, chrome, opera, safari)

+1  A: 

This is not an exhaustive answer as it won't solve your problem, but the Array.push() method works in IE8:

var arr = [];
arr.push({ "name": "Test Name", "value": "Test Value"});
alert(arr[0].name);    // Displays "Test Name"

The above can also be re-written as follows:

var arr = [];
arr[arr.length] = { "name": "Test Name", "value": "Test Value"};
alert(arr[0].name);    // Displays "Test Name"
Daniel Vassallo
+2  A: 

What you have works (even in IE8), you can test it here: http://jsfiddle.net/ZAxzQ/

There must be something outside the question that you're doing to get that error :)

.push() has been around as long as the Array object, I've never seen a browser that doesn't support it...your unsupported error has to be coming from something else.

Nick Craver
+1  A: 

I haven't got access to IE atm, but I'm sure it does support push. Check that sendFormData is considered an array:

Object.prototype.toString.call(sendFormData) === '[object Array]';

Something else IE likes to do, is tell you there is an error on the line after the error occurred, so it may be part of the form.serializeArray() line.

Psytronic
Hmm it comes back as false. Not sure why though. Like I mean the code you see is what I have in my js file. I commented everything else just to make sure too.
chobo2
What does just the first part come back as? ie Object.prototype.toString.call(sendFormData)As it's getting generated via a function I'm not sure if it will show function using that method
Psytronic
A: 

Of course, the easiest another solution is to do something like this:

var sendFormData = $("#form").append("<input id='someuniqueID' type='hidden' name='name' value='test' />").serializeArray();
$("#someuniqueID").remove(); //optional could keep it in there if you wanted
Psytronic
I think we'll have to disagree on what the "easiest" way is here...this is more code, less intuitive, and a *lot* more expensive....I really recommend against this, as the other answers show this *shouldn't* be the problem area anyway, this is a simple array/object operation.
Nick Craver
Okay, maybe not the easiest, but it would still solve the problem. I agree it shouldn't be needed, what he has should work, but if for whatever reason he can't debug it, there is also this option. I don't see how it's less intuitive though, looking at it I can see exactly what's going on. But yes, the overhead will be larger for it.
Psytronic