Is it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept.

I can easily work with hardcoded arrays, but integrating localStorage data is proving to be a challenge for me.

Here's what I've attempted so far (with guidance from another SO user):

$("#submit").click(function () {

    // prepare
    var formData = $("#regForm").serializeArray();
    // get all stored as Array []
    var bookings = JSON.parse(localStorage.getItem('bookings') || '[]');

    for (formData = 0; formData < localStorage.length; formData++) {
    // insert and save
    localStorage.setItem("bookings", JSON.stringify([formData]));
    }
    
});

It works fine without the for loop, but whenever I submit the form again with new data, it replaces the existing information instead of creating a new index.

Essentially, I'm trying to create an appointment scheduler for dog walking where I can view, edit, delete, and display bookings without using databases on the client side.

Should I initialize my array first? How should I approach the for loop? Any help would be greatly appreciated, as I really want to learn but have been struggling with this for hours.

Answer №1

To implement this functionality, you can follow the steps below. Store the new values in a variable and then update the existing values in local storage before exiting.

$("#submit").click(function () {

    var formData = $("#regForm").serializeArray();
    var appointments = JSON.parse(localStorage.getItem('appointments') || '[]');
   
    for (formData = 0; formData < localStorage.length; formData++) {
        appointments.push(formData)   
    }
    localStorage.setItem("appointments", JSON.stringify(appointments));
});

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

Having difficulties retrieving the value of the div in the voting system

Whenever the element with the id #upvote is clicked, the value of the element with the id #vote increases by 1. On the other hand, when the element with the id #downvote is clicked, the value decreases by 1. However, there seems to be an issue where if the ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

The dropdown menu in the navigation bar is overlapping with the datatable, creating a transparency effect

Working on a website layout that features a navbar at the top and a datatable below. However, when hovering over the navbar to reveal subitems, I notice a transparency issue where the navbar overlaps with the datatable. Below is a simplified version of my ...

Is there a way to emphasize text within a string of object array items?

I am currently utilizing the data provided below to pass as props in React. The functionality is working smoothly, but I have a specific requirement to only emphasize the words "target audience" within the text property. Is there a feasible way to achieve ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

Tips for implementing and utilizing an optional parameter within Vue Router

I am trying to set up a route for a specific component that can be accessed in two ways - one with a parameter and one without. I have been looking into optional parameters but haven't found much information. Here is my current route setup: { pa ...

Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function: var string= string.split(' ').join(''); For example, if I input the String: Hello how are you, it should become Hellohowareyou My approach avoids using ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

Is there a way to view the contents of a file uploaded from <input type="file" /> without the need to send it to a server?

Having trouble uploading a JSON file from my local disk to Chrome storage. Whenever I use the <input type="file"> tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...' ImportExport Component: ...

Using vuetify's v-autocomplete component with the options to select all and clear items

I am trying to incorporate a "Filter by values" feature in my application similar to Excel or spreadsheets. However, I am facing difficulty with implementing the 'Select all' and 'Clear' button in v-autocomplete. <v-col> < ...

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

Ensuring the validity of an HTML form by including onClick functionalities for additional form elements

I am working on a form that I put together using various pieces of code that I found online. My knowledge of HTML and JavaScript is very basic. The form includes a button that, when clicked, will add another set of the same form fields. Initially, I added ...

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

Display the JSON boolean value on the webpage using Ajax and Jquery

After using Ajax with a GET request to consume a REST web service, I now have the results displayed in my console. Here are some images related to the REST API I am consuming: However, when attempting to print the results inside a table, only one result ...

Utilizing AngularJS for enhanced data management in DataTables with a customized

I am currently working with AngularJs+DataTable library and I have a specific need to create a custom control that can utilize the exact search function from DataTable, but with a customized user interface. However, when using the search() method, it retur ...

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...