Search code examples
jqueryhtmlvariablespool

Read data -attribute as variable


I have these selection boxes made in HTML with data attributes. Now when somebody clicks one of those boxes i want Jquery to read out the data attribute and use it as a variable. Add 1 or minus 1 to or from a pool. However I'm getting a NaN error. Any ideas of fixing this? Thanks in advance!

HTML:

<label><input type="checkbox" class="selectable one" data="one" />Antwoord 1</label><br />
<label><input type="checkbox" class="selectable two" data="two" />Antwoord 2</label><br />

JQUERY:

one = 0;
two = 0;

$('.selectable').on('click', function(){
    // tell me what pool you are
var thispool = $(this).attr("data");
    // you are now activated
$(this).toggleClass('activated');
    //add +1 if activated, else -1
if ($(this).hasClass('activated')){thispool++;}
else {thispool--;}
});

Solution

  • You can' refer a variable using another variable like that, instead you can use an object as given below

    var counter = {
        one: 0,
        two: 0
    }
    
    $('.selectable').on('click', function () {
        // tell me what pool you are
        var thispool = $(this).attr("data");
        // you are now activated
        $(this).toggleClass('activated');
        //add +1 if activated, else -1
        if ($(this).hasClass('activated')) {
            counter[thispool]++;
        } else {
            counter[thispool]--;
        }
    });
    

    Demo: Fiddle