Search code examples
javascriptjqueryhtmllocal-storageweb-storage

jQuery: Using web storage/local storage on input fields


I am trying so save/retrieve the values of all input fields in a form. Unfortunately, this is not working.
The frustrating part is that I have no idea whats wrong. I already tested for type: both key and value are strings. The event is attached properly, a console.log gets triggered.
Do you see anything that strikes you in this code? Why are no values saved or retrieved?

(function ($) {
    if (typeof (window.localStorage) != "undefined") {
        $.each($("#myform input[type=text]"), function () {
            localStorage.getItem($(this).attr("id"));
        });
        $("#myform input[type=text]").live("change", function () {
            localStorage.setItem($(this).attr("id"), $(this).val());
        });
    }
})(jQuery);

Of course I am testing in a browser that supports web storage and every input has an id.


Solution

    1. .live() is removed in 1.9 and deprecated from 1.7
    2. I don't see any value setter $(this).val(localStorage.getItem($(this).attr("id"))) in the first each loop to populate values.