Populate a set of text areas with jQuery eq() from localStorage

Tags: ,

I have a set of text areas and have set them to save in localStorage. I’ve been trying to use the following code to retrieve those values and put them back into the text areas when the browser reloads.

If I log ('textarea').eq(i).val() it correctly returns an empty string which is the value of the text area before it’s populated. I therefore can’t figure out why the console tells me that the “Left side of assignment is not a reference.” and the code fails.

for (var i = 0; i < $('.box').length; i++) {    
    $('textarea').eq(i).val() = localStorage.getItem(document.title + i);  

I can do this with vanilla JavaScript, but am just curious why the jQuery method I’m applying here doesn’t work.



You’re getting the error because val() is a method, not a property. As such you need to provide the updated value as an argument to the method, like this:

for (var i = 0; i < $('.box').length; i++) {    
  $('textarea').eq(i).val(localStorage.getItem(document.title + i));  

Source: stackoverflow