How do I pass a variable as the HTML localStorage key value?

Posted on 2011-09-19
Medium Priority
Last Modified: 2012-06-27
I want to create a dynamic key name for my localStorage variable within my application based on an incremented numeric value. I want to keep track of a numeric counter and then append the numeric value to a string, and the combined concatenation becomes the localStorage key.

For example:
tctr = 1      I want localStorage.item1 = "value";
tctr = 20    I want localStorage.item20 = "value";

Here is the javascript that I am using to increment the counter variable. I need some help with the variablization (sp?) of the key:

<script type="text/javascript">
    function addCart() {
    localStorage.trxCtr=Number(localStorage.trxCtr) +1;
    var tctr = Number(localStorage.trxCtr) + 1;
    $('body').append('<div id="progress">Cart Updated</div>');
    <!-- history.go(-1); -->
    return true;                   
Question by:kbios
  • 2
LVL 83

Accepted Solution

leakim971 earned 2000 total points
ID: 36562985
use : localStorage["item" + tctr ] = "VALUE";

Author Closing Comment

ID: 36563010
LVL 83

Expert Comment

ID: 36563014
you're welcome, have a nice week!

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article discusses how to implement server side field validation and display customized error messages to the client.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

619 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question