user2596247
user2596247

Reputation: 25

Passing a value from a button in javascript to a function that creates a localStorage variable

I have a survey web app at work to collect data from customers. I'm trying to convert a dozen different functions (one for each option) into one simple function. The "votes" are stored as localStorage variables so that the survey can be reopened each day without losing data. Here is what I have:

<script>

function vote(choice)
{
   if (localStorage.choice)
   {
      localStorage.choice=Number(localStorage.choice)+1;
   }
   else
   {
      localStorage.choice=1;
   }
   alert("Thanks for your input!  Have a nice day");
}

</script>

And then I have buttons in the body that look like this:

<li class="li" onClick="vote(a);">choice 1</li>
<li class="li" onClick="vote(b);">choice 2</li>
<li class="li" onClick="vote(c);">choice 3</li>

Functions work just fine if I have separate ones for each, what am I doing wrong to pass the letters into new localStorage variables?

Upvotes: 2

Views: 991

Answers (2)

Musa
Musa

Reputation: 97682

To use properties of an object dynamically you have to use [] notation

<script>

function vote(choice)
{
   if (localStorage[choice])
   {
      localStorage[choice]=Number(localStorage[choice])+1;
   }
   else
   {
      localStorage[choice]=1;
   }
   alert("Thanks for your input!  Have a nice day");
}

</script>

To pass the letters as strings you have to quote them

<li class="li" onClick="vote('a');">choice 1</li>
<li class="li" onClick="vote('b');">choice 2</li>
<li class="li" onClick="vote('c');">choice 3</li>

DEMO

Upvotes: 4

user1864610
user1864610

Reputation:

a, b, and c are variables. You should use string literals:

<li class="li" onClick="vote('a');">choice 1</li>
<li class="li" onClick="vote('b');">choice 2</li>
<li class="li" onClick="vote('c');">choice 3</li>

Upvotes: 2

Related Questions