tags:

views:

31

answers:

4

I have an array of serialized form information (collected using the serialize functionality in jQuery), and would like to add additional information to it. From what I've read it looks like I need to use the push function in Javascript. Unfortunately when I try this I get an error message saying that 'formData.push is not a function'

My code:

$('#sendForm').live('click',function(){
 var formData = $('#form').serialize();
 alert(formData); //Returns as expected

var newArray = ['test','test2'];  //The new data....
formData.push(newArray);
});

Any ideas on what I'm doing wrong?

Thanks!

+1  A: 

The issue is that .serialize() returns a string, you can't push into a string. I think you want to use jQuery .serializeArray() not .serialize().

Assuming you want a single array of all the elements you'll need to do something like this because pushing one array into another would give you an array within an array...

$('#sendForm').live('click',function(){
 var formData = $('#form').serializeArray();

var newArray = ['test','test2'];  //The new data....
for(i=0;i<newArray.length;i++)
 {
   formData.push(newArray[i]);
 }
});
brendan
Thanks for your answer.
Matt
+1  A: 

formData is a string because the .serialize() method returns a string which is the JSON representation of an html form. The push method applies to arrays only:

newArray.push('some new value');
Darin Dimitrov
Thanks for your answer.
Matt
+1  A: 

You have two problems here:

  1. Javascript's Array.push() only takes one or more scalars, but not another array.

  2. formData probably is a string, which doesn't have push().

Frédéric Hamidi
Thanks for your answer.
Matt
+2  A: 

The other answers almost have it, what you need is to call .serializeArray() then .push() an object with name and value properties, for example:

$('#sendForm').live('click',function(){
   var formData = $('#form').serializeArray();
   formData.push({ name: 'nameOfParam', value: 'valueOfParam' });
   //use formData, for example:
   //$.post("page.html", formData);
   //if you want the serialized string like .serialize(), use $.param(formData);
});
Nick Craver
Thanks for your answer.
Matt