Home > Article > Web Front-end > Use native js to implement form serialization (graphic tutorial)
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 'button': case 'file': case 'reset': case 'submit': break; case 'checkbox': case 'radio': if (!feled.checked) { break; } default: if (arr[feled.name]) { arr[feled.name]=arr[feled.name]+','+feled.value; }else{ arr[feled.name]=feled.value; } } } return arr }
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!