copenndthagen
copenndthagen

Reputation: 50742

jQuery setting attribute value issue

I have some text boxes and on save , I am saving local storage data to them;

$(".formFieldUserData").each(function () {
  var key = $(this).attr("name");
  var value = $(this).attr("value");
  localStorage.setItem(key, value);
}

Now for some reason, even though I enter some value in the text box, $(this).attr("value") returns undefined always.

What is the issue ?

Upvotes: 0

Views: 68

Answers (3)

Peeyush
Peeyush

Reputation: 4828

Try this

$(".formFieldUserData").each(function()
        {
        var key = $(this).attr("name");
        var value = $(this).val();
        localStorage.setItem(key, value);
        }

Upvotes: 0

user1386320
user1386320

Reputation:

This is your solution:

$(".formFieldUserData").each(function() {
    var key = $(this).attr("name");
    var value = $(this).val();

    localStorage.setItem(key, value);
});

Note: "value" attribute of your tag is changable, so you use the $.val() method to get it's value.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

You retrieve form field values using .val(), not .attr("value").

Upvotes: 2

Related Questions