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'开发者_JS百科).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!
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);
});
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');
You have two problems here:
Javascript's Array.push() only takes one or more scalars, but not another array.
formData
probably is a string, which doesn't havepush()
.
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]);
}
});
精彩评论