JS使用json数据自动填充表单
<title>JS使用json数据自动填充表单示例</title> <form name="myform"> text:<input type="text" name="text" /><br /> textarea:<textarea name="textarea"></textarea><br /> radio:<input type="radio" name="radio" value="radio1" />radio1 <input type="radio" name="radio" value="radio2" />radio2<br /> checkbox:<input type="checkbox" name="checkbox" value="checkbox1" />checkbox1 <input type="checkbox" name="checkbox" value="checkbox2" />checkbox2 <input type="checkbox" name="checkbox" value="checkbox3" />checkbox3<br /> checkbox-signle:<input type="checkbox" name="checkbox1" value="checkbox1" />checkbox1<br /> select-single:<select name="selsg"><option value="">...</option><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><br /> select-multiple:<select name="selmul" multiple><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select> </form> <script> function fillData(f, kv) { var attr, el, v, vs; for (attr in kv) { el = f[attr]; if (el) { v = kv[attr]; switch (el.type||el[0].type) { case 'text': case 'textarea': case 'select-one': el.value = v; break; case 'select-multiple': vs = ',' + v.join() + ',';//前后加逗号分隔 for (var i = el.options.length - 1; i >= 0; i--) if (vs.indexOf(',' + el.options[i].value + ',') != -1) el.options[i].selected = true; break; case 'radio': case 'checkbox': var isRadio = el.type == 'radio'; //前后加逗号分隔 if (isRadio) vs = ',' + v.join() + ','; else vs = ',' + v + ','; if (typeof el.length == 'number') {//多个 for (var i = el.length - 1; i >= 0; i--) if (vs.indexOf(',' + el[i].value + ',') != -1) { el[i].checked = true; if (isRadio) break; } } else el.checked = el.value == v;//只有一个 break; } } } } ////////////////////测试 //数据,键名称和表单输入对象同名 var data = { text: 'text value', textarea: 'textarea value', radio: 'radio2', checkbox: ['checkbox1','checkbox3'],//复选框,数组, checkbox1: ['checkbox1'], selsg: '3', selmul:['2','4']//select多选,数组 }; fillData(document.myform, data); </script>
原创文章,转载请注明出处:JS使用json数据自动填充表单
2017-7-13Web开发网