I've noticed that in Firefox an input element maintains its value when the page is reset but not in Safari. Is there a way to maintain the values a user would have typed in JavaScript (no PHP).
I've tried Googling this fairly extensively but every result seems to find this behavior undesirable.
Edit: Not sure what I am doing wrong, this is what I tried:
<input id="myInput" type="text">
<script>
var myInput = document.getElementById("myInput");
if (sessionStorage.getItem("autosave"))
myInput.value = sessionStorage.getItem("autosave");
myInput.addEventListener("change", function() {
sessionStorage.setItem("autosave", myInput.value);
});
</script>
Edit (again): Got it working, thank you:
<input id="myInput" type="text">
<script>
var myInput = document.getElementById("myInput");
window.onload = function() {
if (sessionStorage.getItem("autosave"))
myInput.value = sessionStorage.getItem("autosave");
}
myInput.addEventListener("keyup", function() {
sessionStorage.setItem("autosave", myInput.value);
});
</script>
<input id="persistent_text_field" value=""/>
In your JS
assuming you're using jQuery
$(document).on('ready',function(){
if(sessionStorage.getItem('last_entry')){
$("#persistent_text_field").val(sessionStorage.getItem('last_entry'));
}
$("#persistent_text_field").on("keypress",function(){
sessionStorage.setItem('last_entry',$(this).val());
});
});
EDIT:
Non jQuery Solution? Simple :)
<input id="persistent_text_field" value="" onkeypress="setStorage(this)"/>
In your JavaScript
file call customReset();
in your document load event handler function.
function customReset(){
if(sessionStorage.getItem('last_entry')){
var element = document.getElementById("presistent_text_field");
element.value = sessionStorage.getItem('last_entry');
}
}
function setStorage(element){
sessionStorage.setItem('last_entry',element.value);
}
I think sessionStorage would be ideal for this since localStorage and cookies would persist the values across sessions which is probably not what you would want.
It is a browser behavior, but you can try to override it using cookies to remember entries, if you do not want to use PHP.
document.cookie = "field=value";
You need to store value in cookie or in local storage.
Remember text box value using jQuery cookies