How To Set A Default Value Based On User's Previous Value
I want to have a default value based on what the user put before. For example, if in an input I put '5' I want to see that the value of that input is 5 when I refresh the page, but
Solution 1:
Use local storage:
localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');
let inputDefault = localStorage.getItem('inputDefault');
Here's a more practical example I quickly whipped up:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Local Storage Example</title><scripttype="text/javascript">functionsetLocalStorageValue()
{
let myNumberInputField = document.getElementById('myNumberInput');
let myNewValue = myNumberInputField.value;
letlocalStorage = window.localStorage;
localStorage.setItem('defaultValue', myNewValue);
}
functiongetLocalStoredValue()
{
letlocalStorage = window.localStorage;
let defaultValue = localStorage.getItem('defaultValue');
let myNumberInputField = document.getElementById('myNumberInput');
myNumberInputField.value = defaultValue;
}
</script></head><bodyonload="getLocalStoredValue()"><label>My Number Input
<inputtype="number"id="myNumberInput"value="0"onchange="setLocalStorageValue()"></label></body></html>
Does this answer your question? Note how I am writing back to local storage on the onchange event of the input in question, and I read from local storage when the body of the html loads.
Post a Comment for "How To Set A Default Value Based On User's Previous Value"