Javascript jQuery从表单字段创建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5603117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery create object from form fields
提问by Alex
How can I create a object with a form's fields and values?
如何使用表单的字段和值创建对象?
like this one:
像这个:
{
fields:
{
name: 'foo',
email: '[email protected]',
comment: 'wqeqwtwqtqwtqwet'
}
}
assuming the form looks like this:
假设表单如下所示:
<form>
<input type="text" name="name" value="foo" />
<input type="text" name="email" value="[email protected]" />
<textarea name="comment">wqeqwtwqtqwtqwet</textarea>
</form>
I need to know how can I do this for any form with a single function, not just a particular form.
我需要知道如何对具有单个功能的任何表单执行此操作,而不仅仅是特定表单。
回答by T.J. Crowder
You can do this:
你可以这样做:
var fields = {};
$("#theForm").find(":input").each(function() {
// The selector will match buttons; if you want to filter
// them out, check `this.tagName` and `this.type`; see
// below
fields[this.name] = $(this).val();
});
var obj = {fields: fields}; // You said you wanted an object with a `fields` property, so...
Beware that forms can have fields with repeated names, and what you're trying to do doesn't support that. Also, the orderof fields in HTML forms can be significant. (These are both reasons that serializeArray
works the way it does.)
请注意,表单可以包含具有重复名称的字段,而您尝试执行的操作不支持这种情况。此外,HTML 表单中字段的顺序也很重要。(这两个原因都是serializeArray
如此。)
Note that normal HTML practice is to omit disabled fields. If you want to do that, check this.disabled
before grabbing the value as well.
请注意,正常的 HTML 实践是省略禁用字段。如果您想这样做,请this.disabled
在获取值之前进行检查。
Note that the above (written two years ago) uses a jQuery pseudo-selector. I'm a bit surprised to find that I wrote that. As it says in the documentation for the :input
pseudo-selector, using it means that jQuery can't hand off the selector to the browser's native querySelectorAll
(which nearly all browsers now have).
请注意,上面(两年前写的)使用了 jQuery 伪选择器。我有点惊讶地发现是我写的。正如在:input
伪选择器的文档中所说,使用它意味着 jQuery 不能将选择器交给浏览器的本机querySelectorAll
(现在几乎所有浏览器都有)。
Nowadays I'd probably write:
现在我可能会写:
$("#theForm").find("input, textarea, select, button")...
...if I wanted buttons, or if not then
...如果我想要按钮,或者如果不那么
$("#theForm").find("input, textarea, select")...
...and then filter out input[type="button"]
and input[type="submit"]
inside the each
. E.g. (no buttons at all):
...然后过滤掉input[type="button"]
并input[type="submit"]
在each
. 例如(根本没有按钮):
$("#theForm").find("input, textarea, select").each(function() {
var inputType = this.tagName.toUpperCase() === "INPUT" && this.type.toUpperCase();
if (inputType !== "BUTTON" && inputType !== "SUBMIT") {
// ...include it, either it's an `input` with a different `type`
// or it's a `textarea` or a `select`...
}
});
回答by Hussein
var inputs = $("form :input");
var obj = $.map(inputs, function(x, y) {
return {
Key: x.name,
Value: $(x).val()
};
});
console.log(obj);
回答by Brett Zamir
As per a comment on the http://api.jquery.com/serializeArray/page, you can do:
根据http://api.jquery.com/serializeArray/页面上的评论,您可以执行以下操作:
(function( $ ){
$.fn.serializeJSON=function() {
var json = {};
jQuery.map($(this).serializeArray(), function(n, i){
json[n['name']] = n['value'];
});
return json;
};
})( jQuery );
Then do:
然后做:
var obj = $('form').serializeJSON();
or if you need it with your fields
property, you can modify the function or do this:
或者,如果您的fields
财产需要它,您可以修改该函数或执行以下操作:
var obj = {fields: $('form').serializeJSON()};
Or you can just use serializeArray()
if you don't mind that format of output.
或者,serializeArray()
如果您不介意这种输出格式,则可以使用。
回答by albb
jquery has a serialize() function on froms like $('#myform').serialize()
jquery 在 $('#myform').serialize() 之类的 froms 上有一个 serialize() 函数
is this what you're looking for?
这是你要找的吗?
update: oops, maybe try serializeArray() instead, it should give you an array of name and value.
更新:哎呀,也许试试 serializeArray() 代替,它应该给你一个名称和值的数组。
回答by DDan
回答by Jens H
A lot of complicated ways which do not work in some cases. In the meantime you can use the FormData
许多复杂的方法在某些情况下不起作用。在此期间,您可以使用 FormData
var fields = {};
var myform = document.getElementById('ThisIsTheIDOfMyForm');
var myformdata = new FormData(myform);
for (var [key, value] of myformdata.entries()) {
fields[key] = value;
}
console.log(fields);
is exactly what you want. It handles everything.
正是你想要的。它处理一切。
回答by gion_13
function formsToObj(){
var forms = [];
$('form').each(function(i){
forms[i] = {};
$(this).children('input,textarea,select').each(function(){
forms[i][$(this).attr('name')] = $(this).val();
});
});
return forms;
}
it's a generalized function that creates an object for each form in your page
它是一个通用函数,可为页面中的每个表单创建一个对象
回答by user3504541
This way you catch all values from multiple selects or groups of checkboxes
通过这种方式,您可以从多个选择或复选框组中捕获所有值
function form2obj(form) {
var arr = $(form).serializeArray(), obj = {};
for(var i = 0; i < arr.length; i++) {
if(obj[arr[i].name] === undefined) {
obj[arr[i].name] = arr[i].value;
} else {
if(!(obj[arr[i].name] instanceof Array)) {
obj[arr[i].name] = [obj[arr[i].name]];
}
obj[arr[i].name].push(arr[i].value);
}
}
return obj;
};
回答by Mohammad Fazeli
Simple form code
简单的表单代码
<form id="myForm" name="myForm">
<input type="text" name="email" value="[email protected]"/>
<input type="checkbox" name="gender">
<input type="password" name="pass" value="123"/>
<textarea name="message">Enter Your Message Her</textarea>
</form>
Javascript Code:
Javascript代码:
var data = {};
var element = document.getElementById("form").elements
for (var i = 0; i < element.length; i++) {
switch (element[i].type) {
case "text": data[element[i].name] = element[i].value; break;
case "checkbox": data[element[i].name] = element[i].checked; break;
case "password": data[element[i].name] = element[i].checked; break;
case "textarea": data[element[i].name] = element[i].value; break;
}
}
回答by Jordan From Freer Tool
So I always try to put a wrapper among form submits.
所以我总是尝试在表单提交中放置一个包装器。
This is especially important for form submits that run over ajax.
这对于运行在 ajax 上的表单提交尤其重要。
The first thing to do is grab the form on submit.
首先要做的是在提交时抓取表单。
$(".ajax-form").submit(function(){
var formObject = objectifyForm($(this).serializeArray());
// Do stuff with formObject
// always add return false to stop the form from actually doing a post anywhere
return false;
});
This will wrap any form that has a class of "ajax-form" and send the serializeArray to a function that is called objectify form which will return an object of all of the values of that form.
这将包装任何具有“ajax-form”类的表单,并将 serializeArray 发送到称为 objectify form 的函数,该函数将返回该表单的所有值的对象。
function objectifyForm(formArray) {
returnArray = {};
for (var i = 0; i < formArray.length; i++) {
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}