Save input value on page refresh using sessionStorage

Try the code

See the scripts below.

The script when the element/input is present in DOM.

<input id="field" type="text" />
<button onClick="window.location.reload();">Refresh</button>
  // input to track
  let field = document.getElementById("field"); 
  if (sessionStorage.getItem("autosave")) {
    // Restore a content of the input
    field.value = sessionStorage.getItem("autosave");
  // Listen for changes in the input field
  field.addEventListener("change", function() {
    // save value into sessionStorage object 
    sessionStorage.setItem("autosave", field.value);

Future element storing; the script when the element/input is not yet present in DOM.

<article id="post">
function saveValue(evt) {
	var targetElement =; 
	let selector = 'input#field';
	while (targetElement != null) {
		if (targetElement.matches(selector)) { 
			//console.log('targetElement: ', targetElement);  
			sessionStorage.setItem("autosave", targetElement.value);
// stick EventListener to a preexisting, static element
let rootElement = document.querySelector('#post');  
let event = "change";
rootElement.addEventListener(event, saveValue,	true); 

// we attach the future element with a value from sessionStorage
document.querySelector('#post').innerHTML = '<input id="field" type="text" value="' +sessionStorage.getItem("autosave") + '" />' +
'<button onClick="window.location.reload();">Refresh</button>';

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.