保存html表单字段状态 [英] 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 field. (ex.: >, <, =) After I post my search and returns the result say it i want to change one of my operators but always changes to the first element of it. Is there anything that i can do to "save" the state of the fields?
我可以在会话中做到这一点,但这是一个相当大的形式,所以很难看.
I could do it with sessions but it is a fairly big form so it would be ugly.
谢谢您的回答!
推荐答案
使用 localStorage
的一小段代码:
- 我已安排5秒钟的时间来备份表单上的所有内容.
- 页面加载后,就会从
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 (typeof localStorage["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;}
<form action="">
<strong>Name:</strong> <input type="text" name="name" id="name" /><br>
<strong>Pass:</strong> <input type="password" name="password" id="pass" /><br>
<span id="saving"></span>
</form>
注意: localStorage
是摘要中的沙盒功能.所以在这里行不通.签入JSBin: http://output.jsbin.com/bubukunoke
Note: localStorage
is a sandboxed feature in snippets. So doesn't work here. Check in JSBin: http://output.jsbin.com/bubukunoke
这篇关于保存html表单字段状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!