开发者

jquery form elements to array

开发者 https://www.devze.com 2023-03-31 19:57 出处:网络
I\'m trying to get all form elements to array, then loop through them using jque开发者_StackOverflow社区ry\'s $.each() function and within this function get each element\'s id, and title attributes.

I'm trying to get all form elements to array, then loop through them using jque开发者_StackOverflow社区ry'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?


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

var elems = $('#form_id').find(':input'); // changed this line


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>


I think this could work the way you want:

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


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();

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号