简体   繁体   中英

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.

<HTML>

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

        function
        myfunction2() { //recall code
            document.getElementById('recalledtext').innerHTML =
                localStorage.getItem('mynumber');
        }
    </script>
</head>

<body>
    <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>
</body>

</HTML>

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 (eg // remember code ) with a multiline comment that you close on the same line (ie /* remember code */ )

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