Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain form input fields using jQuery?

I have a form with many input fields.

When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?

like image 430
Vasil Avatar asked Oct 04 '08 01:10

Vasil


People also ask

What jQuery form method can you use to retrieve the input field's data?

The jQuery val() function and serialize() function are built-in functions in jQuery. The val() function can be used to get the first element's value attribute in the set of matched elements. The serializeArray() function is used to get from data; it returns the array of objects by serializing the form data.

How can I get form data with javascript jQuery?

The serializeArray() method creates an array of objects (name and value) by serializing form values. This method can be used to get the form data. Parameter: It does not accept any parameter.

How do I get all inputs from a form?

To iterate through all the inputs in a form you can do this: $("form#formID :input"). each(function(){ var input = $(this); // This is the jquery object of the input, do what you will });

How do you get data from forms?

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.


2 Answers

$('#myForm').submit(function() {     // get all the inputs into an array.     var $inputs = $('#myForm :input');      // not sure if you wanted this, but I thought I'd add it.     // get an associative array of just the values.     var values = {};     $inputs.each(function() {         values[this.name] = $(this).val();     });  }); 

Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray:

var values = {}; $.each($('#myForm').serializeArray(), function(i, field) {     values[field.name] = field.value; }); 

Note that this snippet will fail on <select multiple> elements.

It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+

like image 53
nickf Avatar answered Sep 28 '22 04:09

nickf


Late to the party on this question, but this is even easier:

$('#myForm').submit(function() {     // Get all the forms elements and their values in one step     var values = $(this).serialize();  }); 
like image 25
Lance Rushing Avatar answered Sep 28 '22 04:09

Lance Rushing