使用jQuery获取表单输入字段? [英] Obtain form input fields using jQuery?

查看:162
本文介绍了使用jQuery获取表单输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多输入字段的表单。

I have a form with many input fields.

当我使用jQuery捕获提交表单事件时,是否可以获取该表单的所有输入字段关联数组?

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?

推荐答案

$('#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();
    });

});






感谢Simon_Weaver的提示,这是另一个你可以使用 serializeArray 来做到这一点:


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

请注意,此代码段在< select multiple> 元素。

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

似乎新的HTML 5表单输入不适用于jQuery 1.3版中的 serializeArray 。这适用于版本1.4 +

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+

这篇关于使用jQuery获取表单输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆