当前位置:编程学习 > JAVA >>

jQuery将表单序列化成一个Object对象

验证表单的时候经常需要获取表单中name='***'的元素的值,然后加以判断。jQuery中提供了jQuery.serizlizeArray来将表单序列化成一个数组。尽管如此,数组还是不方便我们操作,我需要讲表单序列化成一个对象。这样更方便于我们操作。
 
下面是代码:
 
view plaincopy to clipboardprint?
/** 
 * @author gaohuia 
 * @site http://www.zeroplace.cn/ 
 */ 
 
(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
 * @site http://www.zeroplace.cn/
 */
 
(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);
 
 
 
 
 
 测试
 
view plaincopy to clipboardprint?
<!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>
</html>
补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,