Keep getting 'undefined, undefined' saved in local storage

Viewed 504

I'm making a day planner app with hour blocks from 0900-1700 where the inputs can be saved into local storage and then are automatically retrieved on page refresh. Having issues with my code currently with it only saving 'undefined, undefined' in the console, and not returning anything on page refresh. Any help is appreciated. Thanks!

HTML:

 <tr class="row" id="15">
            <th scope="time" id="hour15" class="time">15:00</th>
            <td><input type="text" class= "hourinput"/></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>
          <tr class="row" id="16">
            <th scope="time" id="hour16" class="time">16:00</th>
            <td><input type="text" class= "hourinput"/></td>
            <td class="btnContainer">
              <button class="saveBtn"><i class="fas fa-save"></i></button>
            </td>
          </tr>

JS:

// Moment.js to auto-update time on webpage------------------------------------------//
var update = function () {
    date = moment(new Date());
    currentDay.html(date.format('dddd, MMMM Do YYYY, HH:mm:ss a'));
};

$(document).ready(function(){
    currentDay = $('#currentDay');
    update();
    setInterval(update, 1000);
});
// Add input to local storage-------------------------------------------------------//

$('.saveBtn').on('click', function () {
    // Get the values
    var hourinput = $(this).siblings('.hourinput').val();
    var hour = $(this).parent().attr('id');

    // Save data in local storage
    localStorage.setItem(hour, hourinput);
});

  $('#9 .hourinput').val(localStorage.getItem('9'));
  $('#10 .hourinput').val(localStorage.getItem('10'));
  $('#11 .hourinput').val(localStorage.getItem('11'));
  $('#12 .hourinput').val(localStorage.getItem('12'));
  $('#13 .hourinput').val(localStorage.getItem('13'));
  $('#14 .hourinput').val(localStorage.getItem('14'));
  $('#15 .hourinput').val(localStorage.getItem('15'));
  $('#16 .hourinput').val(localStorage.getItem('16'));
  $('#17 .hourinput').val(localStorage.getItem('17'));
1 Answers

Your .saveBtn elements have no siblings. You'll need to traverse up to the .row and then locate the elements / values within.

For example

$(".saveBtn").on("click", function () {
  const row = $(this).closest(".row") // see https://api.jquery.com/closest/

  // Get the values
  const hourinput = row.find(".hourinput").val();
  const hour = row.attr('id');

  // Save data in local storage
  localStorage.setItem(hour, hourinput);
});

FYI, your click event handler could be more efficient by listening at the container level (eg your <table>)

$("table#hours").on("click", ".row[id] .saveBtn", function() {
  // etc
})

You should also make your buttons type="button" to make sure they don't accidentally submit any forms.

Related