2

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>
9
  • try with localStorage in place of window.localStorage? Commented Jan 2, 2021 at 14:18
  • Nope, makes no difference unfortunately.. Commented Jan 2, 2021 at 14:20
  • Hi, update your code with changes you have made . Commented Jan 2, 2021 at 15:58
  • Okay will do that just now. Commented Jan 2, 2021 at 16:00
  • Done @Swati, please see code above Commented Jan 2, 2021 at 16:05

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

13 Comments

No errors after changing some things as there were undefined properties, but doesn't work at all, still not updating.. Thanks for explaining the process though, that is a better way to approach it (I don't really know JS well)
Hi @mplungjan that edit button is dynamically so bind it with some static elements that's the reason this is not working because when edit button is clicked it doesn't call that handler. Also , there is typo while taking value from inputs here parent_form.find('.input:eq(0)').. there is no input with class input .
Hi @swati I have added class input to the innerHTML, can you explain more on the edit button situation? I know thats where the issue is lying but I really can't understand whats going wrong?
Oh wait.. because we load the edit button in the JS and not the HTML, right?
@Caitlin just change your handler i.e : $("#edit").click(function(e) { to $(document).on('click','#edit',function (e) { and try again .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.