2

Possible Duplicate:
Obtain form input fields using jQuery?

I have a form with many input fields.

What is the easiest way to get all the input fields of that form in an array?

Or the Object in Key:Value pair

1
  • 2
    Do you want to get references to the DOM elements or values of the fields? Are the input fields all of the same type (tag) or different ones? Commented Oct 12, 2012 at 10:32

4 Answers 4

6

Use the serializeArray() jQuery function:

var fields = $('#formID').serializeArray();

To get an associative array of the data (a JSON Object with name/value mappings), have a look at the code here: https://stackoverflow.com/a/1186309/349012

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But the solution is not giving me the array specifically the associative ones. But surely helped me to reach the point, i was looking for
So you wanted to create an associative array of keys -> values? (essentially a JSON Object of them?) If so, have a look at this: stackoverflow.com/a/1186309/349012 . It uses the serializeArray function as well, just reformats the data!
3

Object of all the inputs:-

$("form#formId :input").each(function(){
    var input = $(this); // A jquery object of the input
});

or

$('#formId').submit(function() {
    // get the array of all the inputs 
    var $inputs = $('#formId :input');

    // get an associative array of the values
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });
});

This one returns the Key:Value pair -

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

Comments

1

This is pretty easy:

$('input','#formId')

or

$('#formId').find('input');

1 Comment

find api is quite expensive, and it is hanging up my browser... I have couple of tons inputs
-2

Use: var allInputs = $(":input");

2 Comments

This will return all the input type no matter, which form they belongs to
I've seen this get new developers confused. Needs a better selector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.