Local storage in text windows using jQuery

I am new to jquery and localstorage. I want to use localstorage for all text fields 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 could not do this work.

+4
source share
2 answers

You need to set the value

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

+4
source

Try the following:

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:

. , , localStorage object JavaScript. ( , , ), setItem() getItem():

localStorage.setItem('favoriteflavor','vanilla');

favoriteflavor, "vanilla":

var taste = localStorage.getItem('favoriteflavor');
// -> "vanilla"

, - ? - removeItem():

localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
// -> null

! sessionStorage localStorage, , .

. localStorage.

0

Source: https://habr.com/ru/post/1523460/


All Articles