When validating a form, it is often necessary to obtain the value of the element with name='***' in the form and then judge it. jQuery provides jQuery.serizlizeArray to serialize the form into an array. Even so, arrays are still inconvenient for us to operate. I need to serialize the form into an object. This makes it easier for us to operate.
The following is the code:
/** * @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);
Test
<!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>
The above is the content of jQuery serializing the form into an instance of an Object object. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!