user8312352 user8312352 - 5 months ago 54
Javascript Question

Save data to localstorage and display it as innerHTML

I've used these codes for making a simple notes app. It have to store the text box value into localStorage, by pressing the remember button. Then display it but pressing the other button. But it's not working.


function myfunction1() { //remember code var
texttosave = document.getElementById('textline').innerHTML;
localStorage.setItem('mynumber', texttosave);

myfunction2() { //recall code
document.getElementById('recalledtext').innerHTML =

<input type="text" id="textline" />
<button id="rememberer" onclick='myfunction1()'>remember text</button>
<button id="recaller" onclick='myfunction2()'>recall text </button>
<p id="recalledtext">Loading</p>


Max Max
Answer Source

The <input> element's .innerHTML property doesn't change when you enter text. To see what's currently entered into an inputbox, one must use its .value property.

As such

texttosave = document.getElementById('textline').innerHTML ;

needs to become

texttosave = document.getElementById('textline').value ;

and that should do it.

You also, later, linked to your testing website. The code there is

function myfunction1(){ //remember code texttosave = ..........

but that makes texttosave = .......... part of the comment. You need to write

function myfunction1(){ //remember code
    texttosave = ..........

now you've put texttosave = ...... on a separate line, so it's not considered part of the comment.

Alternatively, if you don't want to insert the line breaks to keep the code concise, remove the comments (//remember code, //recall code) and then you can keep them on the same line.

Another alternative is to replace the single line comments (e.g. // remember code) with a multiline comment that you close on the same line (i.e. /* remember code */)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download