Oscar Dulzaides Oscar Dulzaides - 1 year ago 75
HTML Question

Concatenating string plus numeric value of html element to increment a variable

I have a set of counters I want to increment as images are clicked. When the image is clicked I get the value attr of the image. I can then show the appropriate image in a div with name and all and I want to increment it's responding counter. here is the code:

var counter1 = 0;
var counter2 = 0;
var counter3 = 0;
var counter4 = 0;

$('body').click(function(e) {

var target = $(e.target); // Which cat was clicked
value = target.attr("value");
counter = "counter"+ value;
$("img").attr({src:"./images/cat" + value +".png"});
$("h5").html("Cat " + value);

The issue I'm having is that counter = counter1 for example but when I do a counter++ I get NaN. If I just use:

counter1++; // or any other counter

It increments the global counter variable fine.

What am I doing wrong?

Ish Ish
Answer Source

Why don't you do something like this!

//store in array
var counter[1]=0,counter[2]=0,counter[3]=0,counter[4]=0;

//increment the value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download