javascript

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
<form id="form1">
<input type="text" name='username' value="刘大伟"/><br />
<input name="sex" type="radio" value="男" />男<input name="sex" type="radio" value="女" />女<br />
<input name="hobby" type="checkbox" value="上网" />上网
<input name="hobby" type="checkbox" value="看电影" />看电影
<input name="hobby" type="checkbox" value="看书" />看书
<input name="hobby" type="checkbox" value="学习" />学习<br />
<select name="pay">
<option value="1000-2000">1000-2000</option>
<option value="2001-3000">2001-3000</option>
<option value="3001-4000">3001-4000</option>
</select>
<select name="fri" multiple="multiple">
<option>香蕉</option>
<option>西瓜</option>
<option>葡萄</option>
<option>荔枝</option>
<option>草莓</option>
</select>
<button id="serialize-btn">序列化</button>
</form>
<script type="text/javascript">
function serialize(form){
	var arr = [];
	var field='';
	
	for(var i=0;i<form.elements.length;i++){
		 field = form.elements[i];
		switch(field.type){
			case 'select-one':
			case 'select-multiple':
			for(var j=0;j<field.options.length;j++){
			var option = field.options[j];
				if (option.selected){
					var optValue = "";
					if (option.hasAttribute){
						optValue = (option.hasAttribute("value") ? option.value : option.text);
					} else {
						optValue = (option.attributes["value"].specified ? option.value : option.text);//目前知道IE6取不到值,IE7没测试,IE8可以
					}
					arr.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
				}
			}
			break;
			case "radio":       
			case "checkbox":
				if (!field.checked){
					break;
				}
			case undefined:
			case "button":
			case "submit":
			case "reset":
			case "file":
			break;
			default :
			arr.push(encodeURIComponent(field.name)+'='+encodeURIComponent(field.value))
		}
	}
	return arr.join("&");
}
(function(){
	var d = document.getElementById('serialize-btn')
	EventUtil.addHandler(d,'click',function(e){
	var form1 = document.getElementById('form1');
	str = serialize(form1);
	str2 = decodeURIComponent(str);
	alert(str2);
	//alert(str2);
	});
})();
</script>

posted on 2011-07-04 16:01  流浪啊  阅读(770)  评论(0编辑  收藏  举报