<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单序列化</title> </head> <body> <div style="width:350px;height:200px;background-color:YellowGreen"> <form id="myform"> <input type="text" name="text" value="default value"> <br/> <input type="radio" name="sex" value="male" /> Male <input type="radio" name="sex" value="female"/>Female <br/> <input type="checkbox" name="bike"/>My bike. <input type="checkbox" name="car" />My car. <br/> <select name="cars"> <option value="volvo">Volvo</option> <option value="saab">Benz</option> <option value="fiat">BMW</option> <option value="audi">Audi</option> </select> <select name="name" multiple="multiple"> <option value ="zhangsan">zhangsan</option> <option value="lisi">lisi</option> <option value ="wangwu">wangwu</option> <option value="zhaoliu">zhaoliu</option> </select> <br/> <input type="button" onclick="show()" value="show form serialize"> </form> </div> <textarea id="mytext" cols="42" rows="5"></textarea> <script> function serialize(form){ var parts=[], field=null,i,len,j,optLen,option,optValue; for(i=0,len=form.elements.length;i<len;i++){ field=form.elements[i]; switch(field.type){ case "select-one"://单选列表默认处理 case "select-multiple"://对多选列表的处理最复杂,逐项判断和累加 if(field.name.length){ for(j=0,optLen=field.options.length;j<optLen;j++){ option=field.options[j]; if(option.selected){ optValue=""; if(option.hasAttribute){ optValue=(option.hasAttribute("value")? option.value:option.text); }else{ optValue=(option.attributes["value"].specified? option.value:option.text); } parts.push(encodeURIComponent(field.name)+"="+ encodeURIComponent(optValue)); } } } break; case undefined://默认处理 case "file"://默认处理 case "submit"://默认处理 case "reset"://默认处理 case "button"://不处理 break; case "radio"://默认处理 case "checkbox": if(!field.checked){ break; } default://默认处理,要求必须有name属性 if(field.name.length){ parts.push(encodeURIComponent(field.name)+"="+ encodeURIComponent(field.value)); } } } return parts.join("&"); } function show(){ var myform=document.getElementById("myform"); var mytext=document.getElementById("mytext"); mytext.value = serialize(myform); } </script> </body> </html>
时间: 2024-10-22 08:07:11