Reputation: 14038
I'm building a javascript to submit an html form automatically using jQuery. I'm wondering if it's possible to create a javascript method that will return a map of all form elements and values if given an identifier to find the form with. I'd rather use such a method than manually specifying jQuery selectors for each form element.
function form_submit(){
jQuery.ajax({
type: 'post',
url: '/signup/',
data: map_form_elements_values('my_form'),
success: function(data, textStatus, jqXHR){
//foo
}
});
return false;
}
<form id="my_form" action="">
<input class="" id="name" type="text" name="last-name" />
<select class="" id="fruit" type="select" name="fruit-name" />
<option>bananas</option>
</select>
</form>
the goal would be to have map_form_elements_values('my_form')
return a map that can be used by the ajax function. Does anyone know how to do this?
Upvotes: 0
Views: 179
Reputation: 432
You can use serialize()
or serializeArray()
var params = $("#my_form").serialize();
$.post( "/signup/",params,
function(data,textStatus, jqXHR){foo ... } )
See for example
http://api.jquery.com/serialize/
Upvotes: 0
Reputation: 10940
Take a look at the jQuery forms plugin: http://jquery.malsup.com/form/
If you don't need the extra functionality then a simple statement along the lines of:
myData = $("#formToSubmit").serialize();
$.ajax({
type: "POST",
url: "process_form.php",
data: myData,
dataType: "json",
success: function(data) { ....etc
Upvotes: 1
Reputation: 8059
I answered on that recently:
JQuery. How to load inputs values to an array?
jQuery.fn.inputs2obj=function (){
var out={};
var arr=this.filter(':input').each(function () {
e=$(this);
out[e.attr('name')]=e.val();
}).get();
return out;
}
Usage example:
inputs=$('form').find(:input).inputs2obj();
Upvotes: 1