Recover localStorage data in your particular input!

Asked

Viewed 335 times

1

I have a code that dynamically registers input data in the localStorage.

I am trying to recover the data registered in their respective inputs, but without success.

This is the code to recover the data, but only recovers the first data registered:

$("#exibir").click(function(){
        for (var i = 0; i < localStorage.length; i++){  
        var inputs = $('input[type="text"]');
      inputs.val(localStorage.getItem(localStorage.key(i)));
  }
})

JSFIDDLE

Thanks in advance!

1 answer

1

Your problem is not with the localStorage, this part of the code is perfect. The problem is with your variable inputs. Because $('input[type="text"]') returns an array with all <inputs> type text, and therefore you are calling the method .val() in an array of elements.

[ <input>, <input>, <input> ].val("9001");  // Não vai funcionar!

You need to iterate through all the elements in your array inputs and, for each one, call the .val().

  • I modified it yesterday and ended up getting: $("#exibir").on('click', function() {&#xA; $('input[type="text"]').each(function() {&#xA; var id = $(this).attr('id');&#xA; var value = $(this).val();&#xA; var inputs = $('input[id="' + id + '"]');&#xA; inputs.val(localStorage.getItem(id));&#xA; });&#xA;})

  • Ah yes, with .each(). That’s it! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.