0

I'm trying to get all form elements to array, then loop through them using jquery's $.each() function and within this function get each element's id, and title attributes.

I've tried serializeArray(), but I can only get 'name' and 'value' attributes.

I need something that collects all form elements whether it's input (regardless of the type), select, textarea, and regardless whether it has value, is checked or hidden.

Perhaps something like $('#form_id').find('input select textarea'); ?

Any idea how to achieve this?

1
  • Perhaps something like $('#form_id').find('input select textarea');? ... go ahead and try it. Commented Aug 28, 2011 at 10:24

4 Answers 4

3

You can get all form elements with the :input pseudo class:

var elems = $('#form_id').find(':input'); // changed this line
Sign up to request clarification or add additional context in comments.

5 Comments

isn't this one going to only collect 'input' elements?
No, this is a pseudo class that matches all form elements (input, select, textarea, everything)
How is it performance-wise comparing to the suggestion above ($('#form_id')[0].elements) ?
regardless of any benchmarks I guess elements should be mouch faster, it's a native property of forms, nothing to collect.
Don't use :input anymore, it will be removed in the future.
1

Use:

$('#form_id')[0].elements

It will return a nodeList containing all form-elements.

jQuery(
  function($)
  {
    $.each($('#form_id')[0].elements,
           function(i,o)
           {
            var _this=$(o);
            alert('id:'+_this.attr('id')+'\ntitle:'+_this.attr('title'));
           })

  }
);

<edit>
Please Note: the elements-collecttion may also contain elements like fieldset or object, See: http://www.w3.org/TR/html5/forms.html#category-listed
</edit>

1 Comment

that's fine - this is just for the initial validation (client side) - server side has more in depth filtration of all submitted variables
0

I think this could work the way you want:

$('#form_id').children('input, select, textarea')

2 Comments

This will match only immediate children
Use find instead of children
0

You can Use this function

$.fn.serializeAssoc = function() {
    var formData = {};
    this.find('[name]').each(function() {
        formData[this.name] = this.value;  
    })
    return formData;
};

//And Use it like this

objArr = $('#FormID').serializeAssoc();

1 Comment

this will return Associated array with key and value, where key is the form field name and the value is its value in the form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.