码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript示例十(表单序列化)

时间:2014-11-29 16:01:54      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:javascript

<!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>

JavaScript示例十(表单序列化)

标签:javascript

原文地址:http://blog.csdn.net/zjc/article/details/41596313

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!