简体   繁体   中英

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 ?

您可以使用.val()而不是.attr("value")检索表单字段值。

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.

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM