Input text is not being saved. Need code help

I have 11 input fields, each id is incremented by 1:

<input type="text" name="Note1" id="Note1">
<input type="text" name="Note2" id="Note2">

... more fields ...

<input type="text" name="Note11" id="Note11">

This button calls the JS:

<input type="button" value="Save your Notes" onclick="persistData()">

The code loops through the incremented ids. But the input is not saved. Google Chrome tools indicates that the literal strings “note” and “note.value” are saved rather than what the user actually entered. How do I get the actual values entered?

            function persistData()
            {
                if (html5StorageSupported())
                {
                    for (var i = 1; i <= 11; i++)
                    {
                        var note = document.getElementById["Note" + i];
						localStorage.setItem('note','note.value');
                    }
                }

            }

Hi Steve,

I expect what you want to do is this:

localStorage.setItem('note'+i, note.value);

The single quotes around note.value meant that JS was treating it as a string, rather than getting the value of the note node. I’ve assumed that you want to add a digit to the key that your using to store the data, otherwise you’d just be overwriting the value every time the loop runs.

But var note already means note+1, so if we say note+1 on the next line we are incrementing the var again or appending 1 to the id. So Note1 becomes either Note2 or Note11.

No. The ‘note’ is just a string with four characters in it. The way your code is written it will save all of the values into the one single field called ‘note’ and will not save anything in the fields ‘note1’ etc that you expect. Adding the +i to the string appends the number to the name of the field to save the values in so that each gets saved in a different field.

See if you can guess the output of the following examples:


var note = 10;
console.log(note);

'note' = 20;
console.log('note');

var note = 10;
console.log(note);

note = 20;
console.log('note');

var hello = 10;
var world = 20;

console.log(hello + world);
console.log('hello' + 'world');
var data = {
  'a': 1,
  'b': 2,
  'c': 3
};

console.log(data.a);
console.log('data.a');

You’ve also have an error here:


var note = document.getElementById["Note" + i];

document.getElementById is not an array.

Everything with a single-quote around it would show as a literal string in the console. console.log(‘note’) would also show the literal string of note.

This is now working. Thank you!