0

I have been struggling with this for some time now. I have several blocks with hourly time slots and I want to make sure every time a user types something and clicks the save button its saved and even after refreshing the page it still remains on the page until they decide to delete what is written and type something new in that box. my html code below and just so you know I just learning JS so any help will be appreciated.

let time = [];
const addText = (ev) => {
  let newTime = {
    timeData: document.querySelectorAll("#hour Block, #hourBlock1, #hourBlock2").value,

    textData: document.querySelector('.text-input').value
  }
  time.push(newTime);
  localStorage.setItem('My Time', JSON.stringify(time));
}

document.querySelector('.saveButton').addEventListener('click', addText);

document.querySelector('.text-input').value = localStorage.getItem('addText');
<div id="hourblock">
  <div id>9A M</div>
  <input data-hour="9" class="text-input" placeholder=""></inputs>
  <button class="saveButton"><i class="far fa-save fa-2x"></i></button>
</div>
<div id="hourBlock1">
  <div id>10AM</div>
  <input data-hour="10" class="text-input" placeholder=""></inputs>
  <button class="saveButton">
                          <i class="far fa-save fa-2x"></i>   
                        </button>
</div>
<div id="hourBlock2">
  <div id>11AM</div>
  <input data-hour="11" class="text-input" placeholder=""></inputs>
  <button class="saveButton">
                          <i class="far fa-save fa-2x"></i>   
                        </button>
</div>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
Bjorn
  • 13
  • 4
  • Too many issues , so its hard to answer, and even if i rewrite the code to be working, it will not be similar to the above code, instead i will write a list of things to research Your not setting the same key as your are getting, querySelector all on a class cannot set a value – Sam Washington Jan 22 '21 at 17:26
  • What's the problem you are seeing with your code? – Pytth Jan 22 '21 at 17:29
  • @Pytth when i type some text in any of those input boxes and click save and refresh the page, what i typed disappears. not sure if i have written the code correctly for that – Bjorn Jan 22 '21 at 17:53

3 Answers3

0

I don't think that you can keep the data after refreshing the page(using javascript) and variables inside you script. "This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it." In this issue here: https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh#:~:text=This%20is%20possible%20with%20window,localStorage%20or%20window.&text=The%20difference%20is%20that%20sessionStorage,a%20single%20page%20of%20it.

and regarding the issue of clicking on the button, you can use onClick="yourFunction()" like this :

<button class="saveButton" onclick="addText()">
                <i class="far fa-save fa-2x"></i>   
</button>
Elyess Eleuch
  • 141
  • 1
  • 5
0

As you have tagged jQuery, here is a solution in jQuery. I wrote it a while back feel free to port it if you're not using jQuery.

Essentially, add a class to the elements which you want to keep, then it will loop over each one and get the current value for the item, on change/input will save to localStorage.

// iterate over .keep elements, attach storage event, update value if already in storage
$(document)
  .find('.keep')
  .each(function () {
    var elm = $(this);
    var data = JSON.parse(window.localStorage.getItem('input-' + elm.attr('id')));

    if (data && data.value !== null) {
      if (data.type === 'checkbox') {
        $('#' + elm.attr('id')).attr('checked', data.value);
      } else {
        $('#' + elm.attr('id')).val(data.value);
      }
    }

    $(window).on('storage', function (e) {
      if (data) $('#' + elm.attr('id'))[data.type === 'checkbox' ? 'checked' : 'val'](
        window.localStorage.getItem('input-' + elm.attr('id'))
      );
    });
  });

// on .storage change, store value
function store() {
  var elm = $(this);
  let data = {
    type: elm.attr('type') === 'checkbox' ? 'checkbox' : 'input',
    value: elm.attr('type') === 'checkbox' ? elm[0].checked : elm.val()
  }
  window.localStorage.setItem('input-' + elm.attr('id'), JSON.stringify(data));
}

// clear stored items, not efecting other potential keys
function clear() {
  for (var key in window.localStorage) {
    if (key.indexOf('input-') !== -1) {
      let data = JSON.parse(window.localStorage.getItem(key))

      // remove key from storage
      window.localStorage.removeItem(key);

      // clear local element
       if (data.type === 'checkbox') {
        $('#' + key.substring('input-'.length)).prop('checked', false);
      } else {
        $('#' + key.substring('input-'.length)).val('');
      }
    }
  }
}

$(document).on('keyup blur propertychange paste', '.keep', store);
$(document).on('change', 'select.keep', store);
$(document).on('change', 'input[type="checkbox"].keep', store);
$(document).on('click', '.clearkeep', clear);
<input class="keep" id="an-input" />

<select class="keep" id="a-select">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<input type="checkbox" class="keep" id="a-checkbox"/>

<button class="clearkeep">clearkeep</button>

See it working here: https://playcode.io/716777/

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You have many "comprehension" mistakes in your code. I commented them one by one.

// This array should be declared inside the addText function.
// Else, everytimes the user saves, the array will grow...
// And it will end in more data than the amount of inputs.
let time = [];
const addText = (ev) => {
  let newTime = {

    // Here, the targetted elements are divs. There is no value to a div.
    timeData: document.querySelectorAll("#hour Block, #hourBlock1, #hourBlock2").value,

    // Here, you will get a value... 
    // But always the value of the first .text-input of the page.
    textData: document.querySelector('.text-input').value
  }
  time.push(newTime);
  localStorage.setItem('My Time', JSON.stringify(time));
}

// The event handler is setted only for the first button.
document.querySelector('.saveButton').addEventListener('click', addText);

// The first .text-input value will be setted to "null"
// Because there is no "addText" item in localStorage.
// You saved under the item named "My time".
document.querySelector('.text-input').value = localStorage.getItem('addText');

So here is a working code. Have a close look at the differences.

const addText = (ev) => {
  let time = [];

  let fields = document.querySelectorAll(
    "#hourblock, #hourBlock1, #hourBlock2"
  );
  fields.forEach(function (element) {
    time.push({
      field: element.id,
      text: element.querySelector(".text-input").value
    });
  });
  console.log(time);
  localStorage.setItem("timeData", JSON.stringify(time));
};

document.querySelectorAll(".saveButton").forEach(function (btn) {
  btn.addEventListener("click", addText);
});

// on page load
let stored = JSON.parse(localStorage.getItem("timeData"));
if (stored) {
  console.log(stored);
  stored.forEach(function (item) {
    document
      .querySelector("#" + item.field)
      .querySelector(".text-input").value = item.text;
  });
}

This is working in CodePen.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • this worked! thanks a million, yea i noticed i made way too many mistakes. I just started learning JS & jQuery so hopefully i get all this in my head. Again thanks! appreciate it – Bjorn Jan 22 '21 at 18:15