0

I have a few variables

var itemCount = 0;
var pageCount = 0;
var groupCount = 0;

Along with those variables, I have three buttons with data attributes that match these three variables

<button type="button" data-toggle="modal" data-target="#activeQ" data-count="item">ITEM</button>
<button type="button" data-toggle="modal" data-target="#activeQ" data-count="page">PAGE</button>
<button type="button" data-toggle="modal" data-target="#activeQ" data-count="group">GROUP</button>

What I want to do is each time I click a specific button, it increments that variable, ex. I click the ITEM button, itemCount adds 1.

I thought I had the function correct, but when I click it, the count is not incrementing (I am displaying some other information in a modal popup as well):

$('#activeQ').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var aCat = button.data('count');
    var theCount = eval(aCat+"Count");
    theCount++;
    console.log(theCount);
});
Murphy1976
  • 1,415
  • 8
  • 40
  • 88

2 Answers2

2

You can simply use window['varName'] to access a variable :

$('#activeQ').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var aCat = button.data('count');
    window[aCat+"Count"]++;
    console.log(window[aCat+"Count"]);
});
Zenoo
  • 12,670
  • 4
  • 45
  • 69
2

You shouldn't use eval at all..

The best way to do this is to keep your variables in an object:

var counters = {
    item: 0,
    page: 0,
    group: 0
};
$('#activeQ').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var aCat = button.data('count');
    counters[aCat]++;
    console.log(counters);
});

It avoids polluting your global space with variables, and keeps them together as they're related.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42