ricster ricster - 1 year ago 102
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"/>


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

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

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 Source

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

<!DOCTYPE html>


  <label for="time">
  <input type="time" id="time" name="time" min="09:00" max="17:00" value=""/>
  <br />
  <br />
  <button id="setTime">
    Set time
  <button id="test">
    Get time
    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;

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

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download