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--;}
});
有帮助吗?

解决方案 2

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

其他提示

You need to assingn numeric value to data that is 1 not one and the two must be 2 to apply increament or decrement operator.

<label><input type="checkbox" class="selectable one" data="1" />Antwoord 1</label><br />
<label><input type="checkbox" class="selectable two" data="1" />Antwoord 2</label><br />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top