Home > database >  How do I store and retrieve an inputted date using session storage?
How do I store and retrieve an inputted date using session storage?

Time:10-04

function storeBooking(
  start
  ) {
  sessionStorage.start = start;
  }
  
  function getBooking() {
    document.getElementById("confirm_start").textContent = sessionStorage.start;
    }
    
  function prefillcard()
{ 
  document.getElementById("start").value =  sessionStorage.start;
  }

window.addEventListener("DOMContentLoaded", prefillcard);
<form>
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="date of birth" value="2021-10-04" />
<input type="submit" value="Apply">
</form>

So what I've basically set up here is for the date of birth to be stored in session storage and then, if the user decides to fill out the form again in the same browser session, it will auto-fill the date of birth in the form. The only problem is that when I try it, it comes up as dd/mm/yyyy, despite it working for other inputted values. The only difference between those and the date of birth is that those were text inputs and this is a date input. How would I go about storing, retrieving and then auto-filling a form with a date input?

CodePudding user response:

Using setAttribute should work, so something like:

document.getElementById("dateElementID").setAttribute('value', '2021-04-30')

CodePudding user response:

Use window.sessionStorage.setItem("Name", Value)); and window.sessionStorage.getItem("Name");

In your case using JQuery, you can use your own vanilla js if you are not using JQuery

$( "#start" ).on( "change", function() {
  var sdt = $("#start").val();
  window.sessionStorage.setItem("startDT", sdt));
});


function prefillcard() { 
  if (window.sessionStorage.getItem("startDT")) {
   var sdt = window.sessionStorage.getItem("startDT");
   $("#start").val(sdt);
  }
}

Non JQuery version

document.getElementById("start").addEventListener("change", function() {
  var sdt = document.getElementById("start").value;
  window.sessionStorage.setItem("startDT", sdt));
});


function prefillcard() { 
  if (window.sessionStorage.getItem("startDT")) {
   var sdt = window.sessionStorage.getItem("startDT");
   document.getElementById("start").value = sdt;
  }
}
  • Related