Home > Web Front-end > JS Tutorial > body text

Detailed explanation of form formatting plug-in jquery.serializeJSON

小云云
Release: 2018-01-06 10:53:04
Original
3519 people have browsed it

This article mainly brings you a detailed discussion of the form formatting plug-in jquery.serializeJSON. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Preface

When the front-end processes forms that contain a large amount of data submission, in addition to using Form to directly submit and refresh the page, the often encountered requirement is to collect form information into data objects and submit them via Ajax.

When dealing with complex forms, you need to manually judge and process field values ​​one by one, which is very troublesome. The plugin introduced next will solve this problem.

About serializeJSON

Using jquery.serializeJSON, you can call the .serializeJSON() method to serialize the form data into a JS object in a page based on jQuery or Zepto.

Using

Just need to introduce it in jQuery or Zepto

 <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.serializejson.js"></script>
Copy after login

Example

HTML form (supports input, textarea, select and other tags)

<form id="my-profile">
  <!-- simple attribute -->
  <input type="text" name="fullName"       value="Mario Izquierdo" />
 
  <!-- nested attributes -->
  <input type="text" name="address[city]"     value="San Francisco" />
  <input type="text" name="address[state][name]" value="California" />
  <input type="text" name="address[state][abbr]" value="CA" />
 
  <!-- array -->
  <input type="text" name="jobbies[]"       value="code" />
  <input type="text" name="jobbies[]"       value="climbing" />
 
  <!-- textareas, checkboxes ... -->
  <textarea       name="projects[0][name]">serializeJSON</textarea>
  <textarea       name="projects[0][language]">javascript</textarea>
  <input type="hidden"  name="projects[0][popular]" value="0" />
  <input type="checkbox" name="projects[0][popular]" value="1" checked />
 
  <textarea       name="projects[1][name]">tinytest.js</textarea>
  <textarea       name="projects[1][language]">javascript</textarea>
  <input type="hidden"  name="projects[1][popular]" value="0" />
  <input type="checkbox" name="projects[1][popular]" value="1"/>
 
  <!-- select -->
  <select name="selectOne">
    <option value="paper">Paper</option>
    <option value="rock" selected>Rock</option>
    <option value="scissors">Scissors</option>
  </select>
 
  <!-- select multiple options, just name it as an array[] -->
  <select multiple name="selectMultiple[]">
    <option value="red" selected>Red</option>
    <option value="blue" selected>Blue</option>
    <option value="yellow">Yellow</option>
  </select>
</form>
Copy after login

javascript:

$('#my-profile').serializeJSON();
 
// returns =>
{
  fullName: "Mario Izquierdo",
 
  address: {
  city: "San Francisco",
  state: {
    name: "California",
    abbr: "CA"
    }
  },
 
  jobbies: ["code", "climbing"],
 
  projects: {
    '0': { name: "serializeJSON", language: "javascript", popular: "1" },
    '1': { name: "tinytest.js",  language: "javascript", popular: "0" }
  },
 
  selectOne: "rock",
  selectMultiple: ["red", "blue"]
}
Copy after login

The serializeJSON method returns a JS object, not a JSON string. You can use JSON.stringify to convert to a string (note IE8 compatibility).

The Definitive Guide to JavaScript (6th Edition) (Chinese version) http://www.gooln.com/document/452.html

 var jsonString = JSON.stringify(obj);
Copy after login

Specify data type

The obtained attribute value is generally a string, and the type can be specified by HTML: type for forced conversion.

<form>
  <input type="text" name="notype"      value="default type is :string"/>
  <input type="text" name="string:string"  value=":string type overrides parsing options"/>
  <input type="text" name="excluded:skip"  value="Use :skip to not include this field in the result"/>
 
  <input type="text" name="number[1]:number"      value="1"/>
  <input type="text" name="number[1.1]:number"     value="1.1"/>
  <input type="text" name="number[other stuff]:number" value="other stuff"/>
 
  <input type="text" name="boolean[true]:boolean"   value="true"/>
  <input type="text" name="boolean[false]:boolean"   value="false"/>
  <input type="text" name="boolean[0]:boolean"     value="0"/>
 
  <input type="text" name="null[null]:null"      value="null"/>
  <input type="text" name="null[other stuff]:null"   value="other stuff"/>
 
  <input type="text" name="auto[string]:auto"     value="text with stuff"/>
  <input type="text" name="auto[0]:auto"        value="0"/>
  <input type="text" name="auto[1]:auto"        value="1"/>
  <input type="text" name="auto[true]:auto"      value="true"/>
  <input type="text" name="auto[false]:auto"      value="false"/>
  <input type="text" name="auto[null]:auto"      value="null"/>
  <input type="text" name="auto[list]:auto"      value="[1, 2, 3]"/>
 
  <input type="text" name="array[empty]:array"     value="[]"/>
  <input type="text" name="array[list]:array"     value="[1, 2, 3]"/>
 
  <input type="text" name="object[empty]:object"    value="{}"/>
  <input type="text" name="object[dict]:object"    value=&#39;{"my": "stuff"}&#39;/>
</form>
Copy after login
$('form').serializeJSON();
 
// returns =>
{
  "notype": "default type is :string",
  "string": ":string type overrides parsing options",
  // :skip type removes the field from the output
  "number": {
    "1": 1,
    "1.1": 1.1,
    "other stuff": NaN, // <-- Other stuff parses as NaN (Not a Number)
  },
  "boolean": {
    "true": true,
    "false": false,
    "0": false, // <-- "false", "null", "undefined", "", "0" parse as false
  },
  "null": {
    "null": null, // <-- "false", "null", "undefined", "", "0" parse as null
    "other stuff": "other stuff"
  },
  "auto": { // works as the parseAll option
    "string": "text with stuff",
    "0": 0,     // <-- parsed as number
    "1": 1,     // <-- parsed as number
    "true": true,  // <-- parsed as boolean
    "false": false, // <-- parsed as boolean
    "null": null,  // <-- parsed as null
    "list": "[1, 2, 3]" // <-- array and object types are not auto-parsed
  },
  "array": { // <-- works using JSON.parse
    "empty": [],
    "not empty": [1,2,3]
  },
  "object": { // <-- works using JSON.parse
    "empty": {},
    "not empty": {"my": "stuff"}
  }
}
Copy after login

The data type can also be specified in the data-value-type attribute, instead of the :type tag.

<form>
 <input type="text" name="number[1]"   data-value-type="number" value="1"/>
 <input type="text" name="number[1.1]"  data-value-type="number" value="1.1"/>
 <input type="text" name="boolean[true]" data-value-type="boolean" value="true"/>
 <input type="text" name="null[null]"  data-value-type="null"  value="null"/>
 <input type="text" name="auto[string]" data-value-type="auto"  value="0"/>
</form>
Copy after login

options configuration

Default configuration

Values ​​are always strings (unless :types are used in input names)

Keys are always strings (default Does not automatically detect whether it needs to be converted to an array)

Unselected checkboxes will be ignored

Disabled elements will be ignored

Custom configuration

Contains Unchecked checkboxes

serializeJSON supports checkboxUncheckedValue configuration, or you can add the data-unchecked-value attribute to checkboxes.

Default method:

<form>
 <input type="checkbox" name="check1" value="true" checked/>
 <input type="checkbox" name="check2" value="true"/>
 <input type="checkbox" name="check3" value="true"/>
</form>
Copy after login
$('form').serializeJSON();
 
// returns =>
{'check1': 'true'} // Note that check2 and check3 are not included because they are not checked
Copy after login

The above writing method will ignore unchecked check boxes. If you need to include it, you can use the following method:

1. Configure checkboxUncheckedValue

$('form').serializeJSON({checkboxUncheckedValue: "false"});
 
// returns =>
{'check1': 'true', check2: 'false', check3: 'false'}
Copy after login

2. Add data-unchecked-value attribute

<form id="checkboxes">
 <input type="checkbox" name="checked[bool]" value="true" data-unchecked-value="false" checked/>
 <input type="checkbox" name="checked[bin]"  value="1"  data-unchecked-value="0"   checked/>
 <input type="checkbox" name="checked[cool]" value="YUP"                checked/>
 
 <input type="checkbox" name="unchecked[bool]" value="true" data-unchecked-value="false" />
 <input type="checkbox" name="unchecked[bin]"  value="1"  data-unchecked-value="0" />
 <input type="checkbox" name="unchecked[cool]" value="YUP" /> <!-- No unchecked value specified -->
</form>
Copy after login
$('form#checkboxes').serializeJSON(); // Note no option is used
 
// returns =>
{
 'checked': {
  'bool': 'true',
  'bin':  '1',
  'cool': 'YUP'
 },
 'unchecked': {
  'bool': 'false',
  'bin': '0'
  // Note that unchecked cool does not appear, because it doesn't use data-unchecked-value
 }
}
Copy after login

Automatically detect conversion type

The default type is string: string, which can be converted to other types through configuration

$('form').serializeJSON({parseNulls: true, parseNumbers: true});
 
// returns =>
{
 "bool": {
  "true": "true", // booleans are still strings, because parseBooleans was not set
  "false": "false",
 }
 "number": {
  "0": 0, // numbers are parsed because parseNumbers: true
  "1": 1,
  "2.2": 2.2,
  "-2.25": -2.25,
 }
 "null": null, // "null" strings are converted to null becase parseNulls: true
 "string": "text is always string",
 "empty": ""
}
Copy after login

In rare cases, you can use a custom conversion function

var emptyStringsAndZerosToNulls = function(val, inputName) {
 if (val === "") return null; // parse empty strings as nulls
 if (val === 0) return null; // parse 0 as null
 return val;
}
 
$('form').serializeJSON({parseWithFunction: emptyStringsAndZerosToNulls, parseNumbers: true});
 
// returns =>
{
 "bool": {
  "true": "true",
  "false": "false",
 }
 "number": {
  "0": null, // <-- parsed with custom function
  "1": 1,
  "2.2": 2.2,
  "-2.25": -2.25,
 }
 "null": "null",
 "string": "text is always string",
 "empty": null // <-- parsed with custom function
}
Copy after login

Customized type

You can use customTypes to configure custom types or override the default types ($.serializeJSON.defaultOptions.defaultTypes)

<form>
 <input type="text" name="scary:alwaysBoo" value="not boo"/>
 <input type="text" name="str:string"   value="str"/>
 <input type="text" name="number:number"  value="5"/>
</form>
Copy after login
$('form').serializeJSON({
 customTypes: {
  alwaysBoo: function(str) { // value is always a string
   return "boo";
  },
  string: function(str) { // all strings will now end with " override"
   return str + " override";
  }
 }
});
 
// returns =>
{
 "scary": "boo",    // <-- parsed with type :alwaysBoo
 "str": "str override", // <-- parsed with new type :string (instead of the default)
 "number": 5,      // <-- the default :number still works
}
Copy after login

Ignore empty form fields

// Select only imputs that have a non-empty value
$(&#39;form :input[value!=""]&#39;).serializeJSON();
 
// Or filter them from the form
obj = $(&#39;form&#39;).find(&#39;input&#39;).not(&#39;[value=""]&#39;).serializeJSON();
 
// For more complicated filtering, you can use a function
obj = $form.find(&#39;:input&#39;).filter(function () {
     return $.trim(this.value).length > 0
   }).serializeJSON();
Copy after login

Use integer keys as the order of the array

Use useIntKeyAsArrayIndex configuration

<form>
 <input type="text" name="arr[0]" value="foo"/>
 <input type="text" name="arr[1]" value="var"/>
 <input type="text" name="arr[5]" value="inn"/>
</form>
Copy after login

According to the default method, the result is:

$('form').serializeJSON();
 
// returns =>
{'arr': {'0': 'foo', '1': 'var', '5': 'inn' }}
Copy after login

Use useIntKeyAsArrayIndex to convert demerits into an array and set the order

$('form').serializeJSON({useIntKeysAsArrayIndex: true});
 
// returns =>
{'arr': ['foo', 'var', undefined, undefined, undefined, 'inn']}
Copy after login

Default configuration Defaults

All default configurations are defined in $.serializeJSON.defaultOptions and can be modified.

$.serializeJSON.defaultOptions.parseAll = true; // parse booleans, numbers and nulls by default
 
$('form').serializeJSON(); // No options => then use $.serializeJSON.defaultOptions
 
// returns =>
{
 "bool": {
  "true": true,
  "false": false,
 }
 "number": {
  "0": 0,
  "1": 1,
  "2.2": 2.2,
  "-2.25": -2.25,
 }
 "null": null,
 "string": "text is always string",
 "empty": ""
}
Copy after login

Summary

This plug-in supports a very rich configuration and a high degree of customization, which brings great convenience.

Related recommendations:

Install the code formatting plug-in CodeFormatter on Sublime Text 3

Jquery-based web page date formatting plug-in _jquery

Install the code formatting plug-in CodeFormatter

on Sublime Text 3

The above is the detailed content of Detailed explanation of form formatting plug-in jquery.serializeJSON. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template