ricster ricster - 1 month ago 15
Javascript Question

How to use html form time input in Javascript local storage?

I'm trying to get time input in local storage but couldn't succeed it so far.

html part of the time input field of the form:

<label for="time"><p>Start</p></label>
<input type="time" id="time" name="time" min="09:00" max="17:00"/>


javascript:

function getTime(){
globalTime = document.getElementById("time").value;
localStorage.setItem("timeData", globalTime);
}

function inputTime(){
var newTime = localStorage.getItem("timeData");
alert(newTime);
}


When I call the inputTime function, I get empty alert box, which means I can't get the time input.
I'd be grateful if you could tell me what is the reason and how can I fix it.

Answer

Use .addEventListener() to attach input event to #time element. Attach click event to <button> elements to set and get value of localStorage

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <label for="time">
    <p>Start</p>
  </label>
  <input type="time" id="time" name="time" min="09:00" max="17:00" value=""/>
  <br />
  <br />
  <button id="setTime">
    Set time
  </button>
  <button id="test">
    Get time
  </button>
  <script>
    document.getElementById('time').addEventListener('input', getTime);
    document.getElementById('test').addEventListener('click', inputTime);
    document.getElementById('setTime').addEventListener('click', setTime)
    var globalTime;

    function getTime() {
      globalTime = document.getElementById("time").value;
      console.log(globalTime)
    }

    function setTime() {
      localStorage.setItem("timeData", globalTime);
    }

    function inputTime() {
      var newTime = localStorage.getItem("timeData");
      alert(newTime);
    }
  </script>
</body>

</html>

plnkr http://plnkr.co/edit/AzbVoqkGQwLXGlRV9CQd?p=preview