验证表单的时候经常需要获取表单中name='***'的元素的值,然后加以判断。jquery中提供了jquery.serizlizearray来将表单序列化成一个数组。尽管如此,数组还是不方便我们操作,我需要讲表单序列化成一个对象。这样更方便于我们操作。
下面是代码:
/**
* @author gaohuia
*/
(function($){
$.fn.extend({
serializeobject:function(){
if(this.length>1){
return false;
}
var arr=this.serializearray();
var obj=new object;
$.each(arr,function(k,v){
obj[v.name]=v.value;
});
return obj;
}
});
})(jquery);
/**
* @author gaohuia
*/
(function($){
$.fn.extend({
serializeobject:function(){
if(this.length>1){
return false;
}
var arr=this.serializearray();
var obj=new object;
$.each(arr,function(k,v){
obj[v.name]=v.value;
});
return obj;
}
});
})(jquery);
测试
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<fck:meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.formtool.js"></script>
<title>无标题文档</title>
<script language="javascript">
$(function(){
$(":button").click(function(){
var test=$("form").serializeobject();
alert(test.id);
});
});
</script>
</head>
<body>
<form action="" method="get"><input name="id" type="hidden" value="110" />
<input name="test" type="text" />
<input name="" type="button" />
</form>
</body>
</html>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<fck:meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.formtool.js"></script>
<title>无标题文档</title>
<script language="javascript">
$(function(){
$(":button").click(function(){
var test=$("form").serializeobject();
alert(test.id);
});
});
</script>
</head>
<body>
<form action="" method="get"><input name="id" type="hidden" value="110" />
<input name="test" type="text" />
<input name="" type="button" />
</form>
</body>
以上就是jquery将表单序列化成一个object对象的实例的内容。