Open In App

How to convert form data to JavaScript object with jQuery ?

Last Updated : 11 Apr, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

JavaScript objects are complex data types that can store multiple values and properties. Unlike primitive data types that only hold a single value, objects can hold various data types, including other objects, arrays, functions, and more. The inputs given by a user can be converted into objects where multiple inputs can be stored and that are easily accessible. Data that we get from the form can be converted into JavaScript objects using jQuery functions.

The serializeArray() method is a jQuery function that represents a form, it collects all of the form data and converts it into an array of objects.

Syntax:

$(selector).serializeArray();
 

Parameters:

  • selector: form or form elements like text area or input can be selected by the selector parameter.

Approach:

  • Create a form using HTML5.
  • After submitting the form, use the serializeArray() method to collect all the form data and convert it into an array object.
  • With the help of the JavaScript forEach() loop, store the inputs on the client side using console.log().
  • The event.preventDefault() method is used to prevent the form from getting submitted on clicking submit button because we are dealing in the front end, not in the backend. To get the data successfully on the client side, we need to use this function.

Example 1: The following example stores the name of the student and its city name on the client side using the serializeArray() method.

Output: After submitting the form, check if the form data has been converted to a JavaScript object by right-clicking on Submit button and then selecting Inspect, & then selecting the Console tab to get the form data.

 

Example 2: The following example stores the student Id, username, and name of the department on the client side.

Output: After submitting the form, check if the form data has been converted to a JavaScript object. Then, right-click on Submit button and then select Inspect, & select the Console tab to get the form data.

 

Next Article

Similar Reads