JavaScript示例十(表单序列化)
来源:程序员人生 发布时间:2014-12-14 08:58:04 阅读次数:2912次
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF⑻">
<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>
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠