Native JS Implementation Form form serialization

Source: Internet
Author: User

We all know that there is a way to serialize the form in jquery:

1.serialize () method

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

Function: Serializes the contents of the form into a single string.

This way, when Ajax submits the form data, it is not necessary to enumerate each parameter. Simply set the data parameter to $ ("form"). Serialize ().

2.serializeArray () method

Format: var jsondata = $ ("form"). Serializearray ();

Function: Serializes a page form into a JSON-structured object. Note that it is not a JSON string.

For example, [{"Name": "Lihui", "Age": "20"},{...}] get data for Jsondata[0].name

Below we use the original sound JS to implement our form form to serialize the function;

First we set out the steps:

1) First obtain form forms using Byid or forms;

2) Gets an array of all the elements in the form after being fetched by elements;

3) After the traversal judgment type (according to the type of the corresponding object splicing) to achieve the serialization of objects;

The code is as follows:

1 functionFormser (form) {2  varform=document.getElementById (form);3  varArr={};4   for(vari = 0; i < form.elements.length; i++) {5  varFeled=Form.elements[i];6  Switch(feled.type) {7   Caseundefined:8   Case' Button ':9   Case' File ':Ten   Case' Reset ': One   Case' Submit ': A   Break; -   Case' checkbox ': -   Case' Radio ': the  if(!feled.checked) { -   Break; -  } -  default: +  if(Arr[feled.name]) { -arr[feled.name]=arr[feled.name]+ ', ' +Feled.value; +}Else{ Aarr[feled.name]=Feled.value; at   -  }  -  } -  } -  returnarr -},

Native JS Implementation Form form serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.