-2

I'm trying to get into javascript and wrote a short script. What I get when I start the script is "Uncaught SyntaxError: function statement requires a name" and "Uncaught ReferenceError: retrieve is not defined". I don't see why my functions don't work properly. Does anyone have a clue?

<!DOCTYPE html>
<html>

    <head>
        <script>
            function save(){
                alert("in");
                var name = document.getElementById("name").value;
                localStorage.setItem("text",name);
                document.getElementById("out").value=name;
            }
            
            function retrieve(){
                alert("in retr");
                var retrievedData = localStorage.getItem("text");
                if (retrievedData){
                    document.getElementById("name").value=retrievedData;
                }
            }
            
            function delete(){
                document.getElementById("name").value="";
                localStorage.removeItem("text");
            }
        
        </script>
    </head>
    <body onload="retrieve()">
    
        <form >
            <h1>Enter your name</h1>
            <input id ="name" type="text" name="name_input"/>
            <input type="button" name="save" value="save" onclick="save()"/>
            <input type="button" name="rm" value="remove" onclick="delete()"/><br>
            <input type="text" name="out" id="out"/>
        </form>
    </body>


</html>

1 Answers1

2

Open the console. Look at the error messages in order.

Deal with the first problem first.

Uncaught SyntaxError: Unexpected token 'delete'

delete is the name of an operator, you can't use it as the name of a function.

Rename that function and the script trying to define retrieve won't error so retrieve will be defined.


Aside: Your save function won't work for a different reason. Use addEventListener, not onclick attributes.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335