1

I have 4 divs, and depending on what the user clicks I want to set a variable on each of them, which I then want to save using sessionStorage.

<div id="1" onClick="sessionStorage.id=1">Select Me as 1</div>
<div id="2" onClick="sessionStorage.id=2">Select Me as 2</div>
<div id="3" onClick="sessionStorage.id=3">Select Me as 3</div>
<div id="4" onClick="sessionStorage.id=4">Select Me as 4</div>

Then on the <head></head> area I've added:

sessionStorage.setItem("id", "");
sessionStorage.getItem("id");
alert(id);

My problem is that the values are not changing and the onclick doesn't see to be storing the new values.

How can I do this right?

dda
  • 5,700
  • 2
  • 23
  • 33
Satch3000
  • 40,202
  • 83
  • 203
  • 337

3 Answers3

4

Check this demo:

DEMO

  <div id="1" onClick="sessionStorage.id=1">Select Me as 1</div>
  <div id="2" onClick="sessionStorage.id=2">Select Me as 2</div>
  <div id="3" onClick="sessionStorage.id=3">Select Me as 3</div>
  <div id="4" onClick="sessionStorage.id=4">Select Me as 4</div>
  <button onclick="alert(sessionStorage.getItem('id'))">Check Session Value</button>
Akhil Sekharan
  • 11,581
  • 6
  • 34
  • 54
4

I guess what you want to do is:

<div id="1" onClick="sessionStorage.setItem('id', '1')">Select Me 1</div>
<div id="2" onClick="sessionStorage.setItem('id', '2')">Select Me 1</div>
<div id="3" onClick="sessionStorage.setItem('id', '3')">Select Me 1</div>
<div id="4" onClick="sessionStorage.setItem('id', '4')">Select Me 1</div>

<button onClick="alert(sessionStorage.getItem('id'))">click to alert</button>

Live Demo

Matias Elorriaga
  • 7,467
  • 3
  • 34
  • 53
2

Your html to set the values is fine, but I have no idea why use are using setItem() before getItem() as that will clear out the values. All you need in your head to alert the value of id is below:

var id = sessionStorage.getItem("id");
alert(id);

jsFiddle

(just re rerun the fiddle to see the result of the click)

Daniel Gimenez
  • 14,859
  • 2
  • 38
  • 61