javascript 提取表单元素生成用于提交的对象(序列化 html 表单)

时间:2023-01-27 17:31:38
function serialize(f) {
var o = {};
var s = f.getElementsByTagName("select");
for (var i = 0; i < s.length; i++) {
var si = s[i];
var n = si.name;
if (!si.multiple) {
o[n] = si.value;
continue;
}
o[n] = [];
var ops = si.options;
for (var j = 0; j < ops.length; j++) {
var oj = ops[j];
if (oj.selected) {
o[n].push(oj.value || oj.text);
}
}
}
var r = f.querySelectorAll("input");
for (var i = 0; i < r.length; i++) {
var ri = r[i];
var n = ri.name;
if (!(n in o)) {
if (ri.type === "checkbox") {
o[n] = [];
} else {
o[n] = "";
}
}
switch (ri.type) {
case "radio":
if (o[n]) {
continue;
}
if (ri.checked) {
o[n] = ri.value || "on";
}
break;
case "checkbox":
if (ri.checked) {
o[n].push(ri.value || "on");
}
break;
default:
o[n] = ri.value;
break;
}
}
return o;
}