I've got a script in good working order that checks to see if a visitor has been assigned a coupon code but wanted to add functionality that retrieves the coupon code that they were assigned and displays it. Both rely on the localStorage property. The problem I'm running into is that when I display the stored value, it's returning [object HTMLSpanElement]
instead of the value that should be assigned.
Pretty much everything I've found on the issue is due to scope, but I don't see how I have a scope issue...even tried making the variables global in scope and that didn't seem to do anything.
Here is the JS:
if(localStorage.getItem("visited") != "true"){
localStorage.setItem("visited","true");
var codeValue = document.getElementById("code");
localStorage.setItem("code",codeValue);
}
else {
var savedCode = localStorage.getItem("code");
document.getElementById("message").innerHTML = "You've already been assigned coupon code " + savedCode;
}
Here is the relevant HTML:
<span id="message">Your coupon code is: <span id="code">CODE1234</span></span>
When you return to the page after already visiting it, I expect the span text to display You've already been assigned coupon code CODE1234
, but instead it is returning You've already been assigned coupon code [object HTMLSpanElement]
Note that part of the script was something I had created before and put in production, and I'm basically piggybacking off of that functionality. Previously, if getItem("visited") != "true"
returned false, it popped up an alert box and said you'd already been given a code, then redirected you to another page.