How can JavaScript/jQuery be used to update LocalStorage Objects when editing a form?

Having trouble pinpointing an issue with my code. Despite making modifications, the values in localStorage are not updating as expected. Any suggestions on what may be causing this problem?

Note: Changing const idx to const i resulted in only the final value being updated for all bookings, which was unexpected. Attempted to change the i value but encountered an error regarding initialization.

bookings.findIndex(booking => bookings[i].fname == fname && bookings[i].lname == lname);

Below is the updated code:

    // ~~~ add bookings to localStorage

var bookings = JSON.parse(localStorage.getItem("bookings")) || [];

window.onload = showBooking();


$("#submit").click(function() {
    var newBookings = {
        fname: $('#fname').val(),
        lname: $('#lname').val()
    }
    bookings.push(newBookings);

    var json = JSON.stringify(bookings);
    window.localStorage.setItem("bookings", json);
    showBooking();
});

// ~~~ edit bookings in localStorage

$(document).on('click','#edit',function (e) {
    e.preventDefault();

    var parent_form = $(this.form);

    var fname = parent_form.find('.input:eq(0)').val();
    var lname = parent_form.find('.input:eq(1)').val();

    const i = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);

    deleteBooking(i);

    bookings.push({
        fname,
        lname
    });

    var json = JSON.stringify(bookings);
    window.localStorage.setItem("bookings", json);


});


// ~~~ display bookings in browser

function showBooking() {
    var bookingResult = document.getElementById("result");
    var ul = document.createElement("ul");
    bookingResult.innerHTML = "";
    for (let i = 0; i < bookings.length; i++) {
        bookingResult.innerHTML += `<div class="card card-body bg-light m-4"> 
<h3>${bookings[i].fname + " " + bookings[i].lname} 
<button onclick="deleteBooking(${i})" class="btn btn-danger text-light ">Delete</button>
<button onclick="editBooking(${i})" class="btn btn-danger text-light ">Edit</button>
</h3>                            
</div>`;
    }
}

// ~~~ edit bookings in browser

function editBooking(i) {
    $('#result').hide();
    var currentItem = document.getElementById("currentItem");
    var editBooking = document.getElementById("editAppt");


    currentItem.innerHTML += `<div class="card card-body bg-light m-4"> 
<h3>${bookings[i].fname + " " + bookings[i].lname} </h3>                            
</div>`;

    editBooking.innerHTML = `<input type="text" class="input" id="fname_${i}" placeholder="${bookings[i].fname}" name="${bookings[i].fname}" value="${bookings[i].fname}" required>
<input type="text" class="input" id="lname_${i}" placeholder="${bookings[i].lname}" name="${bookings[i].lname}" value="${bookings[i].lname}" required>
<input id="edit" type="submit" value="Edit">`;

}

// ~~~ delete bookings from localStorage

function deleteBooking(i) {
    bookings.splice(i, 1);
    localStorage.setItem("bookings", JSON.stringify(bookings));
    showBooking();
}

HTML form used:

<form id="regForm" name="regForm" action="" class="col-sm-6">

    <div class="row">
        <input type="text" class="input" id="fname" placeholder="First Name" name="fname" required>
        <input type="text" class="input" id="lname"placeholder="Last Name" name="lname" required>
        <input id="submit" type="submit" value="Submit">
    </div>

</form>

<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
<div id="editAppt" class="row"></div>

Answer №1

Consider the following adjustments:

  1. Make sure to handle both bookings and bookingItems separately
  2. If there are changes made, ensure they are saved before moving on
  3. Avoid excessive parsing of localStorage by only reading once and writing when necessary
  4. To prevent duplicate IDs, delegate and utilize class names instead
  5. Consistency is key, use jQuery for element creation and adding events - such as removing a form element closest to a delete button through delegates

Check below for how to locate a booking based on names

const idx = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);

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

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Can the load() function retrieve an element along with its descendants?

While experimenting with the jQuery load() command, I encountered an interesting scenario. My code looked something like this: $('<div id="box" />').load('my.html div#content', function(){ etc. To my surprise, I was able to retri ...

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

Tips for removing borders from the AJAX Loading icon in jQuery Mobile

Is there a way to remove the borders from the default jQuery Mobile loading icon? I am attempting to call the ajax-loading.gif icon before any page creation. $(document).on('pagebeforecreate', '[data-role="page"]', function ( ...

Is it possible for Graphfana to utilize JSON data retrieved directly from a webpage?

My server generates a web page containing JSON data from an application that monitors temperature. I'm curious to find out if there's a possibility for Grafana to track and visualize this data on a dashboard. Appreciate your assistance! ...

Using a function as a prop in Vue js to retrieve data from an API

I am facing an issue with a component that I want to decouple from the data fetching implementation. My goal is to be able to pass a data fetching callback as a prop. The reason for this is so that I can easily mock the data fetching process in storybook. ...

Creating POJOs by parsing two JSON files, with one file referencing the other

I currently have two JSON files named occupations.json and people.json. The first file contains an array of occupations: [ { "name": "developer", "salary": "90000"}, { "name": "designer", "salary": "80000"}, { "name": "manager", "salary": "700 ...

"Add a touch of magic to your webpage with text effects that appear

I am looking to create a glowing text effect, and I stumbled upon this resource. http://jsfiddle.net/karim79/G3J6V/1/ However, the client prefers the text effect to appear after the page loads, rather than on hover. Unfortunately, I do not have experien ...

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

What steps can you take to resolve the "TypeError: Cannot read property 'id' of undefined" issue?

I have been developing an app that involves using databases to add items for users based on their user ID, which is their username. However, whenever I attempt to add an item, I encounter an error that I can't seem to troubleshoot. The error message r ...

Tips on Enhancing a Fetch Query in Laravel with the Help of Ajax

I am encountering difficulty fetching a list of cities with over 40,000 entries. The main issue is the lack of optimization as my browser becomes unresponsive while loading the city data. Within my Laravel Controller, the code snippet below showcases how I ...

Running Jest encounters errors when there is ES6 syntax present in the node modules of a create-react-app project

Currently, I am working on a project using create-react-app and attempting to perform unit testing on a component from office-ui-fabric-react using Jest and Enzyme. The most recent version of office-ui-fabric-react utilizes es6 syntax which is causing iss ...

Utilizing jQuery to execute functions from various files simultaneously with a single load statement

My goal is to achieve a basic include with jQuery, which involves loading functions from multiple files when the DOM is ready. However, this task proved to be more complex than anticipated: index.html <script type="text/javascript" src="res/scripts.js ...

Using AJAX and jQuery to refresh a specific div when a specific button is clicked

I have a function that uses AJAX to update votes when clicked. Here is the code: $(function() { $(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var dat ...

Enhancing productivity with tools for developers and effortless tab navigation

During my development process, I always keep the developer tools open on one or more of my tabs. However, I noticed that when I switch to a tab where the developer tools were not previously open, a resize event is triggered. Strangely, this event causes el ...

Having trouble accessing an object in a post request with Axios, VueJS, and Laravel

I'm facing an issue with sending my post data to the controller in order to access it via an object. Although the data is being passed successfully, I'm unable to access any of the items within that object, which seems quite perplexing. Below is ...

Python application for flattening and mapping nested JSON keys

I am completely new to JSON and struggling with understanding the structure of a JSON file. Here is an example of a JSON file I have: {"employeeId":{"0":02100, "1":02101, "2":02102,... "1000000":021000000}, "employeeName":{"0":"Smith", "1":"John", "2":" ...