Save Html Form Field State
Today I came up with something interesting at one of my projects. I have a search box with several fields(ex.: licence plate, date of buy, state) and some of them has an operator f
Solution 1:
A small snippet for you using localStorage
:
- I have timed as 5 seconds to take a backup of everything on the form.
- Loads the stuff from the
localStorage
once the page is loaded.
window.onload = function () {
if (typeof(Storage) !== "undefined") {
if (typeoflocalStorage["name"] !== "undefined") {
document.getElementById("name").value = localStorage["name"] ? localStorage["name"] : "";
document.getElementById("pass").value = localStorage["pass"] ? localStorage["pass"] : "";
}
// Code for localStorage/sessionStorage.setInterval(function () {
document.getElementById("saving").innerHTML = 'Saving...';
setTimeout(function () {
document.getElementById("saving").innerHTML = '';
}, 500);
localStorage.setItem("name", document.getElementById("name").value);
localStorage.setItem("pass", document.getElementById("pass").value);
}, 5000);
}
};
strong {display: inline-block; width: 50px;}
<formaction=""><strong>Name:</strong><inputtype="text"name="name"id="name" /><br><strong>Pass:</strong><inputtype="password"name="password"id="pass" /><br><spanid="saving"></span></form>
Note:localStorage
is a sandboxed feature in snippets. So doesn't work here. Check in JSBin: http://output.jsbin.com/bubukunoke
Solution 2:
I solved the problem with sessions at the end.
When I post the form I save all of the content into a session and in the View I check if it exists and if yes I set it to as the field value.
Post a Comment for "Save Html Form Field State"