user2807681
user2807681

Reputation: 99

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.

Upvotes: 0

Views: 2811

Answers (2)

sebapalus
sebapalus

Reputation: 556

  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.

Upvotes: 0

Manolo
Manolo

Reputation: 26360

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

(from JQuery documentation)

So my guess is that you have two options:

$("#myform input[type=text]").on("change", function () {
        localStorage.setItem($(this).attr("id"), $(this).val());
 });

or

$("#myform input[type=text]").delegate("change", function () {
        localStorage.setItem($(this).attr("id"), $(this).val());
 });

Upvotes: 1

Related Questions