Home > Web Front-end > JS Tutorial > Use native js to implement form serialization (graphic tutorial)

Use native js to implement form serialization (graphic tutorial)

亚连
Release: 2018-05-18 14:24:15
Original
2621 people have browsed it

The following is the native js I compiled for you to implement form serialization. Interested students can take a look.

First introduce the corresponding form serialization method in jquery:

1.serialize() method

Format: var data = $ ("form").serialize();

Function: Serialize the form content into a string.

In this way, when submitting form data with ajax, there is no need to list each parameter one by one. Just set the data parameter to $("form").serialize().

2.serializeArray() method

Format: var jsonData = $("form").serializeArray();

Function: Serialize the page form into a JSON structure Object. Note that it is not a JSON string.

For example, [{"name":"lihui", "age":"20"},{...}] gets the data as jsonData[0].name;

below We use original js to implement our form serialization function;

First we list the steps:

1) First get the form using ById or forms;

2) After obtaining, obtain the array of all elements in the form through elements;

3) Then traverse to determine the type (corresponding object splicing according to the type) to implement the serialized object;

The code is as follows:

function formser(form){
  var form=document.getElementById(form);
  var arr={};
 for (var i = 0; i < form.elements.length; i++) {
  var feled=form.elements[i];
  switch(feled.type) {
 case undefined:
 case &#39;button&#39;:
  case &#39;file&#39;:
  case &#39;reset&#39;:
  case &#39;submit&#39;:
  break;
  case &#39;checkbox&#39;:
  case &#39;radio&#39;:
  if (!feled.checked) {
  break;
  }
  default:
  if (arr[feled.name]) {
  arr[feled.name]=arr[feled.name]+&#39;,&#39;+feled.value;
  }else{
  arr[feled.name]=feled.value;
  }
  }
  }
  return arr
}
Copy after login

The above is the native js I compiled for everyone to implement form form serialization. I hope it will be helpful to everyone in the future.

Related articles:

How to implement sliding puzzle verification code in JS

vuejs中v -Detailed explanation of using if and v-show

##SourceNode.jsDetailed explanation of registration email activation instructions

The above is the detailed content of Use native js to implement form serialization (graphic tutorial). 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