Jquery 循环形式输入
我有一个有很多输入的表单。我想获得每个id和值,然后将它们放入$.load方法中。我试过这个:Jquery 循环形式输入,jquery,forms,serialization,loops,Jquery,Forms,Serialization,Loops,我有一个有很多输入的表单。我想获得每个id和值,然后将它们放入$.load方法中。我试过这个: $("#form input").each(function() { var name = $(this).attr("id"); var value = $(this).attr("value"); $.extend(params, { name, value }); }); 然后使用$.load(“script.php”,params) 但很明显,
$("#form input").each(function() {
var name = $(this).attr("id");
var value = $(this).attr("value");
$.extend(params, {
name, value
});
});
然后使用$.load(“script.php”,params)代码>
但很明显,它不起作用。在params中,我只有一个元素“name”。我不确定是否也应该使用extend方法。要序列化表单,您可以使用以下类似方法:
假设您要构建的是一个具有两个属性(名称/值)的对象数组,下面是获取该数组的代码:
var myparams = [];
$("form input").each(function() {
// build an object literal to store your values
var o = {
name: this.id, // no need to turn 'this' in a jquery object to get the ID
value: $(this).val() // use .val() to get the value
};
myparams.push(o); // add to the array
});
这似乎有效
var params={};
$('input').each(function(){
params[$(this).attr('id')] = $(this).val();
});
console.log(params);
输出
bar: "bar"
bof: "bof"
foo: "foo"
请参见此处的将.serialize()
表单元素的$('#form')
和AJAX进行序列化不是更简单吗?表单元素是基于它们的名称
,而不是id
属性拾取的。
bar: "bar"
bof: "bof"
foo: "foo"