Home>

This code serializes the form element as a json object:

<! Doctype html>
 <html xmlns=http://www.w3.org/1999/xhtml>
 <head>
 <title>jquery extension-form serialize to json object</title>
 <meta http-equiv=content-type content="text/html;charset=utf-8">
 <script type="text/javascript" src="jquery-1.10.2.js"></script>
</head>
<body>
<p><b>results:</b></p>
<form>
 <select name="amodel.single">
 <option>single</option>
 <option selected>single2</option>
 </select>
 <br /><br />
 <select name="amodel.multiple" multiple="multiple">
 <option selected="selected">multiple</option>
 <option>multiple2</option>
 <option selected="selected">multiple3</option>
 </select>
 <br /><br />
 <input type="checkbox" name="amodel.check" value="check1" />check1
 <input type="checkbox" name="amodel.check" value="check2" checked="checked" /✓
 <br /><br />
 <input type="radio" name="amodel.radio" value="radio1" checked="checked" />radio1
 <input type="radio" name="amodel.radio" value="radio2" />radio2
</form>
<script type="text/javascript">
 var fields=$("select,:radio"). serializearray ();
 var o=(};
 jquery.each (fields, function (i, fields) {
  if (o [this.name]) {
   /*
   There may be multiple identical labels in a form.
For example, if there are multiple labels,   Then after you insert the first label in the json object o, continue to insert,   Then at this time o [label] already exists in o,So you have to treat o [label] as a nested array
   * /
   //If o [label] is not nested in an array
   if (! o [this.name] .push) {
    o [this.name]=[o [this.name]];//Initialize o [label] as a nested array,Such as o={a, [a, b, c]}
   }
   o [this.name] .push (this.value || "");//Insert value into o [label]
  } else {
   o [this.name]=this.value || "";//Insert o [label] in o for the first time
  }
 });
 $("#results"). append (json.stringify (o));
 console.log (o);//Output with firebug
</script>
</body>
</html>

The result is shown below:

  • Previous IOS observer design pattern
  • Next ThinkPHP's solution to pagination failure when using post query