joreland
joreland

Reputation: 3

Setting local storage from dynamically created textarea's values'

I am creating a work day calendar application for a school project where the user can save notes that will remain on the screen after the window is refreshed. I dynamically added text area and button elements with corresponding id's (among some other elements) for the typical 9am-5pm hours like so:

for (let i = 9; i <= 17; i++) {
  let textAreaEl = $('<textarea>')
    .addClass('description col-8 col-md-10')
    .attr('id', 'note-' + i)
    .attr('rows', '3');
  let saveBtnEl = $('<button>')
    .addClass('btn saveBtn col-2 col-md-1')
    .attr('aria-label', 'save-' + i);
}

Now I am using the setItem and getItem methods of local storage to store and retrieve the value of the textareas. I can properly save specific text area values with their corresponding save buttons, but I can only save one. Also, when I refresh the page the getItem method is setting the value of the one stored value to every textarea element. Here is the localStorage code:

let savedNote = localStorage.getItem('savedNote');
if (savedNote !== null) {
  $('.description').val(savedNote);
    console.log(savedNote);
}

$('.saveBtn').on('click', function () {
  let note = $(this).prev('.description').val();
  localStorage.setItem('savedNote', note); 
    
});

The localStorage after clicking the sibling button of the text area

The application after refreshing the window

I sort of have an understanding of why I can only save one element and why every textarea value is being filled after the refresh, I have only created one savedNote value which is storing values based on the element previous to the button clicked. Then when I use getItem it is providing values to the textarea element based on the class which will indeed change all values. I'm stuck trying to figure out how I could create a loop that iterates through the textarea elements based on their id's (as they are given id's like such: id="note-9", id="note-10" etc...). Hopefully this makes sense, I am a little new to JS and JQuery.

Upvotes: 0

Views: 74

Answers (0)

Related Questions