[英]Local storage saving every input and checkbox value on a page
Is there a way to save every input field and checkbox without much code? 有没有一种方法可以在没有太多代码的情况下保存每个输入字段和复选框? I have this and it's working great to save separate input fields, with a
class="stored"
on each: 我有这个功能,它可以很好地保存单独的输入字段,每个字段都带有
class="stored"
:
$(document).ready(function () {
function init() {
if (localStorage["fname"]) {
$('#fname').val(localStorage["fname"]);
}
}
init();
});
$('.stored').change(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
<div class="form-group required">
<label class="label_fn control-label" for="fname">First name (required):</label>
<input id="fname" name="fname" type="text" placeholder="" class="input_fn form-control stored">
</div>
But is there a way to, say, set a class of "something-container"
on the container div and using this script as a base, save all input fields to storage and have them remain populated in the fields until the user clears the session? 但是,有没有办法在容器div上设置一类
"something-container"
,并以该脚本为基础,将所有输入字段保存到存储中,并在用户清除会话之前将其填充在字段中?
Yes, simply change your selector in the change
event from ".stored"
to ".something-container input"
. 是的,只需在
change
事件".stored"
选择器从".stored"
change
为".something-container input"
。 In the Init
method you'll want to do something like this: 在
Init
方法中,您需要执行以下操作:
$(".something-container input").each(function () {
$(this).val(localStorage[$(this).attr("name")])
}
A side note, the .change
binding should likely get done inside the $(document).ready
method as well. 附带说明,
.change
绑定也应该在$(document).ready
方法内完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.