如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
对于语义ui/formantic ui,有一个内置的行为get值:
const fields = $("#myForm.ui.form").form('get values');
const jsonStr = JSON.stringify(fields);
看见https://fomantic-ui.com/behaviors/form.html#/settings
get-values(标识符)返回与标识符数组匹配的元素值的对象。如果未通过IDS,将返回所有字段
其他回答
另一个答案
document.addEventListener(“DOMContentLoaded”,函数(){setInterval(函数){var form=document.getElementById('form')||document.querySelector('form[name=“userprofile”]');var json=Array.from(new FormData(form)).map(函数(e,i){this[e[0]〕=e[1];return this;}.bind({}))[0];console.log(json)document.querySelector('#asJSON').value=JSON.stringify(JSON);}, 1000);})<form name=“userprofile”id=“form”><p>名称<input-type=“text”Name=“firstname”value=“John”/></p><p>姓氏<input name=“lastname”value=“Smith”/></p><p>工作<input name=“employment[name]”value=“inc,inc.”/></p><p>工作时间:<input name=“employment[since]”value=“2017”/></p><p>照片<input-type=“file”/></p><p>发送<input-type=“submit”/></p></form>JSON:<textarea id=“asJSON”></textarea>
表单数据:https://developer.mozilla.org/en-US/docs/Web/API/FormData
Tobias Cohen解决方案的固定版本。此函数正确处理0和“”等错误值。
jQuery.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
以及一个CoffeeScript版本,方便您编写代码:
jQuery.fn.serializeObject = ->
arrayData = @serializeArray()
objectData = {}
$.each arrayData, ->
if @value?
value = @value
else
value = ''
if objectData[@name]?
unless objectData[@name].push
objectData[@name] = [objectData[@name]]
objectData[@name].push value
else
objectData[@name] = value
return objectData
这将处理具有相同名称的多个select或偶数元素:
$.fn.formToJSON = function(){
pairStr=this.serialize();
let rObj={};
pairStr.split(`&`).forEach((vp)=> {
prop=vp.split(`=`)[0];
val=vp.split(`=`)[1];
if(rObj.hasOwnProperty(prop)) {
if (Array.isArray(rObj[prop])) {
rObj[prop].push(val);
} else {
rObj[prop]=[rObj[prop]];
rObj[prop].push(val);
}
} else {
rObj[prop]=val;
}
});
return JSON.stringify(rObj);
}
创建地图并循环所有字段,保存其值。
var params = {};
$("#form").find("*[name]").each(function(){
params[this.getAttribute("name")] = this.value;
});
如果要发送带有JSON的表单,则必须在发送字符串时删除[]。您可以使用jQuery函数serializeObject()实现这一点:
var frm = $(document.myform);
var data = JSON.stringify(frm.serializeObject());
$.fn.serializeObject = function() {
var o = {};
//var a = this.serializeArray();
$(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select').each(function() {
if ($(this).attr('type') == 'hidden') { //If checkbox is checked do not take the hidden field
var $parent = $(this).parent();
var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
if ($chb != null) {
if ($chb.prop('checked')) return;
}
}
if (this.name === null || this.name === undefined || this.name === '')
return;
var elemValue = null;
if ($(this).is('select'))
elemValue = $(this).find('option:selected').val();
else
elemValue = this.value;
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(elemValue || '');
}
else {
o[this.name] = elemValue || '';
}
});
return o;
}