Search code examples
javascripthtmllocalstackangular2-localstorage

Save data to localstorage, display it by innerHTML ,if there is nothing in the data,show the original text of span(Visitors)


I've made this code for saving a form data to localstorage

<HTML>

<head>
    <script>
        function myfunction1() { texttosave = document.getElementById('textline').value; localStorage.setItem('mynumber', texttosave); } function myfunction2() { document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } function myfunction3() { localStorage.removeItem('mynumber'); return ''; }
    </script>
</head>

<body onload='myfunction2()'>
    <input type="text" id="textline" placeholder="Enter Your Name" /> <button id="rememberer"
        onclick='myfunction1()'>Save</button> <button id="recaller" onclick='myfunction3()'>Delete Your Name</button>
    <br>
    Welcome<span id="recalledtext">Dear Visitor,</span> Refresh the page to see changes
</body>

</HTML>

If you enter your name and click the save button,it saves your name into localstorage. Then if you Refresh the page,You will see "Welcome 'Your Name' Refresh the page to see changes" below the form.You can simply delete your name from localstorage by clicking the delete button. All that tasks are working. But if the visitor didn't saved any name or if the visitor click over the delete button, I want to show the original text which is inside the span(Dear Visitor,). Please tell me how to do that


Solution

  • You can make a new myfunction4() which resets the value (although perhaps you can find a better name for it than that):

    function myfunction4(){
        document.getElementById('recalledtext').innerHTML = "Dear visitor,";
    }
    

    And you can call it when the user clicks delete:

    function myfunction3() {
        localStorage.removeItem('mynumber'); 
        myfunction4();
        return '';
    }
    

    When the name saved is blank, you don't really need to do anything at all.

    function myfunction2() {
        if(localStorage.getItem('mynumber')!="") {
            document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); 
        }
    }