jquery

Saving text inside a span to sessionStorage


I have text within a span that I'd like to save to sessionStorage, but I'm having issues. This is an example of what I'm trying to save/copy to the session.

<span class='myspanvalue'>Text and 1234</span>

I started with:

$(document).ready(function() {
   $(".mybutton").click(function() {
    var valueToStore = $('.myspanvalue').data();
    sessionStorage.setItem("myKey", valueToStore);

    console.log("Value saved to sessionStorage:", valueToStore);
  });
});

And got this console message: Value saved to sessionStorage: {}[[Prototype]]: Object

Then I tried this:

$(document).ready(function() {
  $(".mybutton").click(function() {
       var valueToStore = myspanvalue;       
    myspanvalue = document.getElementById(".myspanvalue").innerHTML 
            sessionStorage.setItem("myKey", valueToStore);

    console.log("Value saved to sessionStorage:", valueToStore);
  });
});

I also tried:

myspanvalue = document.querySelector('span#myspanvalue');

Both gave this console message: Uncaught ReferenceError: myspanvalue is not defined

Session Storage always shows “myKey” as the key, and [object Object] as the value.

I've spent two days looking at message boards and info sites, like w3schools, with no luck. I'm leaning towards my needing to use json.stringify, but I don't want to dive into learning all about that (at this moment) unless that is the solution – in which case I will dive in.


Solution

  • Your

    sessionStorage.setItem("myKey", valueToStore);
    

    stored the object. You need to stringify it, like

    sessionStorage.setItem("myKey", JSON.stringify(valueToStore));
    

    Here

           var valueToStore = myspanvalue;       
        myspanvalue = document.getElementById(".myspanvalue").innerHTML 
                sessionStorage.setItem("myKey", valueToStore);
    

    You try to use myspanvalue before creating it. Create it before using it:

                let myspanvalue = document.getElementById(".myspanvalue").innerHTML 
                var valueToStore = myspanvalue;       
                sessionStorage.setItem("myKey", valueToStore);