factor_za factor_za - 5 months ago 13
Javascript Question

Get value of data attribute to use as a comparison?

I have a loop that generates random numbers and positions in order to create 4 answers that a user can choose from.

The next step I am wanting to implement is to determine the value of the clicked button while comparing that to the position of the correct answer. However it keeps returning the data attribute I set to create the buttons position as undefined. I am not sure why this is the case.



// ===============================================
// BUTTON AND ANSWER GENERATOR
// ===============================================
function numberGenerator(){
var goodAnswer = 21,
gaPosition = Math.floor(Math.random() * 4),
allAnswers = [],
buttonArea = $("#answerOptions"),
answer,
buttonPosition = 0;

for(n = 0; n < 4; n++) {
buttonPosition++;
if(n == gaPosition) {
answer = goodAnswer;
} else {
do {
answer = Math.floor((Math.random() * 100) + 1);
}
while(answer == goodAnswer || allAnswers.indexOf(answer) !== -1);
}

allAnswers.push(answer);
input = $('<div class="col-xs-6"><button class="btn btn-primary answerButton" data-button="'+buttonPosition+'">'+ answer +'</button></div>');
input.appendTo(buttonArea);
}

console.log(allAnswers);
console.log(gaPosition);

$(document).on('click', '.answerButton' , function(){
var clickedButton = $(this).data('data-button');
console.log(clickedButton);
if(clickedButton == gaPosition) {
alert("Correct!");
}
else {
alert("Incorrect!");
}
});
}



Answer

You can omit the "data" from the data-button.

// getter
var clickedButton = $(this).data('button');

// setter (just to elaborate)
var example = 'string' || 0;
$(this).data('button', example);

jQuery API for data()