Guide to saving HTML form data into localstorage as a JSON string through JavaScript

What's the best way to retrieve form values for localStorage as a JSON string without using JQuery? I tried using a for loop but I'm having trouble.. any hints would be greatly appreciated (I'm still new at this). Thank you!

 <input type="submit" name="submit" value="submitOrder" onclick="return getValues();">

var userOrder='';
function getValues(){
    for(var i=0; i < document.forms[0].length - 1; i++){
        console.log(document.forms[0][i]);
        return false;
    }
}    

localStorage.setItem('userOrder',JSON.stringify(userOrder));
console.log(localStorage.getItem('userOrder'));

Answer №1

One way to achieve this functionality is by following these steps:

HTML:

<form id="myform">
  <input type="text" name="test">
  <input type="submit" value="submitOrder">
</form>

JavaScript:

const userOrder = {};

function getValues(e) {
  // Convert form elements object into an array
  const elements = Array.prototype.slice.call(e.target.elements);

  // Iterate through the array to store input name & value pairs
  elements.forEach((el) => {
    if (el.type !== "submit") {
      userOrder[el.name] = el.value;
    }
  });

  // Save the data to localStorage
  localStorage.setItem('userOrder', JSON.stringify(userOrder));
}  

document.getElementById("myform").addEventListener("submit", getValues);

Answer №2

Avoid using jQuery with this method. By utilizing ES 2015 syntax, you can still support older browsers by running it through babel for compatibility.

// To loop through all forms within the document as an array,
// use the [...stuff] to convert the nodelist into a real array
let userdata = [...document.forms].map(form => {
  // Iterate through the form's relevant elements 
  // and create key/value pairs for the name/object
  return [...form.elements].reduce((obj, el) => {
    // Ensure every form control has a name attribute
    obj[el.name] = el.value;
    return obj;
  }, {});
});

// Convert the data object into a JSON string and store it
localStorage.setItem('userOrder', JSON.stringify(userdata));

// Retrieve and parse the stored data back into an object
let data = JSON.parse(localStorage.getItem('userOrder'));

If the forms have ids (recommended), you can also utilize reduce in the outer layer instead of map and hash on the form id:

let userdata = [...document.forms].reduce((result, frm) => {
  result[frm.id] = [...frm.elements].reduce((obj, el) => {

Continue with similar methods for further functionalities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with controlling the speed of ajax requests while using vue-multiselect and lodash

I am working on a Vue application that includes a vue-multiselect component. My goal is to load the multiselect options via ajax. To achieve this, I am using lodash.throttle to limit the frequency of ajax requests as the user types in the search criteria ...

Check my Twitter feed every 10 seconds

I'm attempting to access my Twitter feed (sent from a smartphone) for a local application, as Twitter is remote... I created a jQuery + JSON script, but with my overly frequent setInterval at 25ms, I quickly hit the limit of 150 requests per hour and ...

What steps should I take to ensure that this JSON.stringify function functions as intended?

I'm facing a minor challenge in formatting my arrays into the desired JSON structure. Here's the code I've used: var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}] var data = []; for (var i = 0; i < arrData.length ...

JavaScript Hangman Game Malfunctioning

I am in the process of creating a basic hangman game to be played on a web browser. Whenever the user clicks a button, it triggers a function called pickWord(): <button onclick="pickWord()" id="restart">Choose A Word</button> This functi ...

Unlocking the Power of JSON: Techniques for Manipulating JSON Data in MongoDB

Below is a basic JSON structure that needs to be manipulated before storing it in MongoDB: { "id": "ff59ab34cc59ff59ab34cc59", "name": "Joe", "surname": "Cocker" } To achieve the necessary transformations for MongoDB, the "ff59ab34cc59ff59ab34cc59" ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Transferring binary fragments to Node.js for assembly into a complete file. Creating a file

Hey there, I'm in a bit of a bind. I'm trying to send file chunks using multiple XMLHttpRequest requests and then receive these parts in Node.js to reconstruct the original file from the binary data. The issue I'm facing is that the final f ...

Vue.js watcher fails to observe changes in v-model

I'm encountering an issue with vue.js. I have set it up so that when a new item is added, it is saved to local storage. However, I also want the item to be saved to local storage when editing it in the input field. I thought this should work because o ...

Dynamically filling a second dropdown menu according to the selection made in the first dropdown using AJAX and PHP

Help! I'm feeling a bit overwhelmed. Even though this question has been answered multiple times, I still can't figure it out. There must be something so obvious that I am missing. I want the options in the second select input to be populated dyn ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

AngularJS not displaying loader during AJAX request

While utilizing ajax requests with $http, there seems to be a delay due to the server operation taking longer than expected. I have implemented a loader to display while processing the request, but unfortunately it is not showing up on the page. Even after ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

The JSON data is incomplete and the APIs are not being generated. Is there anyone available to investigate this

Here is the code snippet that defines a RESTful API endpoint for retrieving available database connections: @Path("/dbresource") @Api(value = "Available_Connections", description = "List of available DB connections to generate the report", position = 1) p ...

Adjust Camera Position in A-Frame Scene Based on Scrolling Movement

I've been struggling to find a solution for this particular scenario in Aframe. I want to create an embedded Aframe scene as the background of a webpage and have the camera move along a path as the user scrolls down the page. I've set up a scene ...

Having trouble establishing a default route with React Router v5

I am facing an issue with setting the default route to the home page in react router v5. Despite trying several methods, I cannot get it to work as expected. Index.js import React from "react"; import ReactDOM from "react-dom"; import ...

Extract nested JSON data and load it into a pandas DataFrame

How can I convert the provided Json data into a pandas DataFrame? The JSON is nested and contains multiple lists and dictionaries. { "status": "success", "data": { "resultType": "vector", ...

Node.js exec command encountering an uninformative error message and not executing properly

Here is the snippet of code that needs to be executed cp.exec("cc -Wall /tmp/test.c -o /tmp/test", function(e, stdout, stderr) { if (e) { var errorstr = "There was an error during compilation: "+ e.message.toString() ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

Efficiently Loading JavaScript Files in Django for Optimal Website Performance

I have a Django blog app with a Post model that includes a field called body. This field may contain Latex, so I utilize MathJax.js, as well as code snippets, for which I use highlight.js. Sometimes I use both, and other times neither. Is there a way to a ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...