Skip to content
the poor coder

store object in input value

Poor Man
Published
Reading time
1 min read
On this page

How to store object in input value?#

Storing an object in an input value is a common task in web development. It can be useful when you need to send complex data between client-side and server-side, or when you want to save data in the local storage.

Method 1: JSON.stringify() and JSON.parse()#

The easiest way to store an object in an input value is to convert it to a string using JSON.stringify() method, and then set the string as the input value. When you need to retrieve the object, you can parse the string back to an object using JSON.parse() method.

Text

let person = { name: "Raju", age: 25 };
let input = document.getElementById("input");
input.value = JSON.stringify(person); // storing the object in input value

// retrieving the object from input value
let retrievedObject = JSON.parse(input.value);
console.log(retrievedObject.name); // output: "Raju"
console.log(retrievedObject.age); // output: 25

Method 2: Using a hidden input field#

You can also create a hidden input field and set its value as the object. This method is useful when you want to submit the object with a form.

Text


  
  Submit



let person = { name: "Raju", age: 25 };
let input = document.getElementById("person");
input.value = JSON.stringify(person); // storing the object in hidden input value

In the server-side code, you can retrieve the object by parsing the input value:

Text

$person = json_decode($_POST['person']);
echo $person->name; // output: "Raju"
echo $person->age; // output: 25

Both of these methods are easy to implement and can be useful in different situations. Choose the method that best suits your needs.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC