user347284
user347284

Reputation:

Javascript array index is a var

I'm working on a website with Jquery tabs dynamically generated. Each tab has an ID.

For the purpose of my script I need to know how many times the user has clicked in a tab.

To record the number of clicks I was thinking of doing an array like this:

var i  = new Array(my_tab_id);
(...)
i[my_tab_id] = 0;

Where my_tab_id dynamically changes depending on the tab we're in. Sadly, it doesn't seem like the value of my_tab_id is translated into the array. I don't have i[5] = 0, i[6] = 0, etc. but rather i[my_tab_id], which doesn't help more than a simple var.

Any advice? Thanks!

Upvotes: 3

Views: 296

Answers (4)

pauloya
pauloya

Reputation: 2563

I think I understand your problem.
You are saying that the var i only has one element. This happens because the var i is newly instantiated every time you open a new tab. I'm guessing every tab is a new page or at least is a new context for var i.
If you want to keep an instance of an object (like an array) in between different pages, take a look at jStorage, it allows you to keep data locally on the browser and it makes it easier to maintain context between page loads.
If all tabs are on the same page then the solution is easier, you need to keep the array in a global variable for the page.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222438

Are you sure my_tab_id is an integer when i[my_tab_id] = 0; is called?

Upvotes: 0

jessegavin
jessegavin

Reputation: 75690

This should allow you to store the click count onto each tab using the .data() function in jQuery each time a tab is clicked.

$('#example').bind('tabsselect', function(event, ui) {
    var count = parseInt(ui.tab.data("clickCount"));
    if (isNaN(count)) count = 0;
    count++;
    ui.tab.data("clickCount", count);
});

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30092

In that case you shouldn't use an array, you should use an object, which you can treat like a hash.

var o = {};
var id = 'x';
o[id] = 1;
alert(o[id]);

Upvotes: 7

Related Questions