Caitlin
Caitlin

Reputation: 531

Updating LocalStorage Objects Based on Edit Form with JavaScript/jQuery?

I asked a question earlier with answers which didn't help, I still haven't been able to figure out where my issue is. Originally I thought it was because I had two IDs named the same but this was not the issue.. The form submits and there are no errors but it does not update the values in localStorage?

Edit: After changing const idx to const i the value at position [2] (or final value) would update for every booking (regardless of index). I thought of maybe changing the i value to below but it gives error i is defined before it is initialised?

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

Here's what I have (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);

    //    showBooking();

});


// ~~~ display bookings in browser

function showBooking() {
    var bookingResult = document.getElementById("result");
    var ul = document.createElement("ul");
    //   var bookingItems = JSON.parse(localStorage.getItem("bookings")) || [];
    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) {
    //  $('#regForm').hide();
    $('#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();
}

My HTML form:

<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>

Upvotes: 2

Views: 759

Answers (1)

mplungjan
mplungjan

Reputation: 178375

There are several changes you need to consider

  1. You have bookings AND bookingItems
  2. You do some changes (I assume there will be some destination change) but do not save them
  3. You parse the localStorage far too often. Not needed. Only read once and write when modified
  4. You cannot have duplicate IDs so you need to delegate and use class names
  5. Be consistent and use jQuery to create elements and to add events- for example the delete button should be d er legates and remove its closest form element

Here is how to find the booking based on names

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

Upvotes: 1

Related Questions