遍历form表单里面的表单元素,取其value
form.elements 获取所有表单元素
form 表单
<form action="http://localhost:1995/api/post" class="form" method="post">
<input type="text" name="name" value="ajanuw">
<input type="text" name="name" value="alone">
<input type="text" name="name" value="xxx" disabled>
<input type="text" value="bbb">
<input type="password" name="pass" value="123">
<button type="submit">p</button>
<div>
<p>单选框 性别</p>
男:
<input type="radio" name="sex" checked value="男"> 女:
<input type="radio" name="sex" checked value="女">
</div>
<div>
足球:
<input type="checkbox" name="zuqiu" checked value="足球"> 篮球:
<input type="checkbox" name="lanqiu" checked value="蓝球">
</div>
<p>
<textarea name="wneben" id="" cols="30" rows="10">hello world</textarea>
</p>
<div>
<select name="form-select" multiple class="asd">
<option value="a" selected>aaa</option>
<option value="b" selected>bbb</option>
<option selected>
hello
<p>hello</p>
</option>
</select>
</div>
<fieldset name="group-from">
<legend>健康信息</legend>
身高:
<input type="text" name="height" value="111" /> 体重:
<input type="text" name="weight" value="222" />
</fieldset>
</form>
js 代码
let l = console.log;
function qs(s) {
return document.querySelector(s)
}
let toArray = Array.from;
let f = qs('.form')
let body = {}
scanDOM(f);
function scanDOM(box) {
let eles = toArray(box.children)
for (let ele of eles) {
if (ele.children.length && ele.nodeName !== 'SELECT' && ele.nodeName !== 'FIELDSET') { // select元素没有必要递归,表单包也暂时不用遍历
scanDOM(ele)
} else {
let nodeName = ele.nodeName.toLowerCase();
let formElementp = (v) => v === 'input' || v === 'select' || v === 'textarea' || v === 'fieldset';
if (formElementp(nodeName)) { // 确认元素是表单元素
if (ele.disabled === true) continue; // 如果元素为禁用则跳过
let k, v;
k = ele.name;
if (!k) continue; // 没有name的表单元素跳过
if (ele.type === 'radio') { // 单选按钮时,需要判断是否为选中状态
if (!ele.checked) continue;
v = ele.value;
} else if (ele.type === 'checkbox') {
if (!ele.checked) continue;
v = ele.value;
} else {
if (nodeName === 'select' && ele.multiple) {
let vs = []; // 收集所有多选状态下的 selected的value,
let options = toArray(ele.children);
for (let o of options) {
vs.push(o.value)
}
v = vs;
} else if (nodeName === 'fieldset') {
scanDOM(ele)
} else {
v = ele.value;
}
}
if(v === undefined) continue;
let alive = k in body;
if (alive) { // 已经存在相应的name
let ov = body[k]
if (Object.prototype.toString.call(body[k]) === '[object Array]') {
body[k] = ov.concat(v)
} else {
body[k] = [ov, v]
}
} else {
body[k] = v;
}
}
}
}
}
l(body)