I currently use the following code to save input after browser refresh.
<style>textarea, input {
width:100%;
height:50px
}
</style>
<textarea class='' id='thetext' onkeyup='saveValue(this)'/><br/><br/>
<button id='' onclick='shift()'>Shift</button><br/><br/>
<script>
var input = document.getElementById("thetext");
function shift() { input.value = input.value.toUpperCase()}
</script>
<script>document.getElementById("thetext").value = getSavedValue("thetext");
function saveValue(e){
var id = e.id;
var val = e.value;
localStorage.setItem(id, val);
}
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}</script>
When a user enters something in the textarea, and leaves the window, the textarea gets stored in local storage, thanks to the onkeyup event listener.
However, if the user presses the shift button and leaves the browser, the uppercase text value doesn't get stored in textarea because there's no onkeyup action after button press.
I tried various event listeners instead of onkeyup, like onblur, onunload but none of them are working. Is there any event listener which can record the actions then and there? Or any way else?
PS - This code isn't working on Stackoverflow, don't know why, however it's working on my webpage. So, Please ignore this issue.
You can just call the saveValue() method after you´ve done all your stuff you need with the input.
just update the saved value by calling the savevalue() method you defined like this input.value = input.value.replace(); input.saveValue()
Run this in your own environment.
<form>
<input name="first" placeholder="first" />
<input name="last" placeholder="last" />
</form>
<script>
const form = document.querySelector('form');
const FORM_DATA = 'FORM-DATA';
window.addEventListener('DOMContentLoaded', () => {
const fromStorage = localStorage.getItem(FORM_DATA);
if (!fromStorage) return;
const json = JSON.parse(fromStorage);
for (const input of form.querySelectorAll('input')) {
input.value = json[input.name];
}
});
form.addEventListener('keyup', () => {
const formData = Object.fromEntries([...new FormData(form)]);
localStorage.setItem(FORM_DATA, JSON.stringify(formData));
});
</script>