Michie
Michie

Reputation: 81

trying to use local storage to get value JS

i'm trying to make a 'welcome, abby' by clicking submit button but using local storage. Also, it shouldn't be 'welcome, '. it turns out keep refresh after i click the button

<p>
<label for="inName" >What is your name?</label>
<input type="text" id="inName" name="f_name"/>
    </p>

<!-- GET COLOUR-->
<p>
<label for="inColor" >What is your favourite colour? </label>
<input type="color" id="inColor" name="f_color" />
</p>
        
<p>
<input type="submit" id="submit" value="Click to save" />
    </p>

js

var name=document.getElementById("inName");
var backColor=document.getElementById("inColor");
var btn=document.getElementById("submit");
var btndel=document.getElementById("btnDel");

btn.onsubmit=getData;
btndel.onclick=deleteData;

function getData(){
    var temp={
        Name:name.value,
        bckcolor:backColor.value
    }
   
   localStorage.setItem("temp", JSON.stringify(temp));
    
    console.log(localStorage.getItem("temp"));

}

Upvotes: 0

Views: 83

Answers (2)

cheesyMan
cheesyMan

Reputation: 1510

onsubmit is a <form> event, not <input>event.

moreover, if you call both onclick and onsubmit, onclick fires before onsubmit, so you delete data before you get.

Upvotes: 2

merzy
merzy

Reputation: 17

You'd have to perform the variable assignment operation after the function, like so

function getData(){
    var temp={
        Name:name.value,
        bckcolor:backColor.value
    }
   
   localStorage.setItem("temp", JSON.stringify(temp));
    
    console.log(localStorage.getItem("temp"));

}
btn.onsubmit = getData;

and try it again. JavaScript is executed from the top of the file, to the bottom, so when it reads btn.onsubmit=getData;, it looks above it and says 'I don't see a variable declared called getData, it doesn't exist.' There's many other ways to execute this, of course, but I think that is what you're trying to do. I also do not see the deleteData variable declared anywhere.

Upvotes: 0

Related Questions