使用jQuery获取表单输入字段?

本文翻译自: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? 当我使用jQuery捕获提交表单事件时,是否可以在关联数组中获取该表单的所有输入字段?


#1楼

参考:https://stackoom.com/question/i5y/使用jQuery获取表单输入字段


#2楼

serialize() is the best method. serialize()是最好的方法。 @ Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. @ Christopher Parker说Nickf的anwser完成了更多,但它没有考虑到表单可能包含textarea和选择菜单。 It is far better to use serialize() and then manipulate that as you need to. 最好使用serialize()然后根据需要进行操作。 Data from serialize() can be used in either an Ajax post or get, so there is no issue there. 来自serialize()的数据可用于Ajax post或get,因此没有问题。


#3楼

Sometimes I find getting one at a time is more useful. 有时我发现一次获得一个更有用。 For that, there's this: 为此,有这样的:

var input_name = "firstname";
var input = $("#form_id :input[name='"+input_name+"']"); 

#4楼

If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following: 如果您需要从输入中获取多个值,并且您使用[]来定义具有多个值的输入,则可以使用以下命令:

$('#contentform').find('input, textarea, select').each(function(x, field) {
    if (field.name) {
        if (field.name.indexOf('[]')>0) {
            if (!$.isArray(data[field.name])) {
               data[field.name]=new Array();
            }
            data[field.name].push(field.value);
        } else {
            data[field.name]=field.value;
        }
    }                   
});

#5楼

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

});

#6楼

Associative? 联想? Not without some work, but you can use generic selectors: 不是没有一些工作,但你可以使用泛型选择器:

var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值