store object in input value
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.
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.
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:
$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.