Question

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.

Était-ce utile?

La solution 2

  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.

Autres conseils

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());
 });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top