Categories
Development

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>
<script>
  // 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);
  });
</script>

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

<article id="post">
   ...
</article>
<script>
function saveValue(evt) {
	var targetElement = evt.target; 
	let selector = 'input#field';
	while (targetElement != null) {
		if (targetElement.matches(selector)) { 
			//console.log('targetElement: ', targetElement);  
			sessionStorage.setItem("autosave", targetElement.value);
			return;
		} 
	}
}
// 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>';
</script>

Leave a Reply

Your email address will not be published.

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