Reputation: 695
I am new in jquery and localstorage. I want to use localstorage to all textboxes using jquery.
<input id="in-1" type="text" />
<br />
<input id="in-2" type="text" />
<br />
<input id="in-3" type="text" />
<br />
<input id="in-4" type="text" />
<br />
I am trying to follow this script:
(function ($) {
if (typeof (window.localStorage) != "undefined") {
$.each($("input[type=text]"), function () {
localStorage.getItem($(this).attr("id")));
});
$("input[type=text]").on("change", function () {
localStorage.setItem($(this).attr("id"), $(this).val());
});
}
})(jQuery);
But I couldn't make this work.
Upvotes: 4
Views: 1853
Reputation: 8590
Try this:
jQuery(function ($) {
if (typeof (window.localStorage) != "undefined") {
// will get value of specific id from the browser localStorage and set to the input
$("input[type=text]").val(function () {
return localStorage.getItem(this.id);
});
// will set values in browser localStorage for further reference
$("input[type=text]").on("change", function () {
localStorage.setItem(this.id, $(this).val());
});
}
});
Here is a working Demo.
Details:
Using local storage in modern browsers is ridiculously easy. All you have to do is modify the localStorage object
in JavaScript. You can do that directly or (and this is probably cleaner) use the setItem()
and getItem()
method:
localStorage.setItem('favoriteflavor','vanilla');
If you read out the favoriteflavor key, you will get back “vanilla”:
var taste = localStorage.getItem('favoriteflavor');
// -> "vanilla"
To remove the item, you can use — can you guess? — the removeItem()
method:
localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
// -> null
That’s it! You can also use sessionStorage instead of localStorage if you want the data to be maintained only until the browser window closes.
The complete reference here. It should give you more knowledge about localStorage
.
Upvotes: 1
Reputation: 388316
You need to set the value back
jQuery(function ($) {
if (typeof (window.localStorage) != "undefined") {
//set the value to the text fields
$("input[type=text]").val(function () {
return localStorage.getItem(this.id);
});
$("input[type=text]").on("change", function () {
localStorage.setItem(this.id, $(this).val());
});
}
});
Demo: Fiddle
Upvotes: 5