I’m making a small game for a school project, and basically there are 20 boxes. 10 boxes have a value of -2, 5 boxes have a value of 2, 3 boxes have a value of 0, and 2 boxes have a value of -5 and 5. So my question is, how can I determine which box was clicked with which value?
Code to initialize my boxes:
shuffle(numbers); // number.length is 20
for(var i = 0; i < numbers.length; ++i)
{
$('#buttons').append('<button class="boxes" id="' + numbers[i] + '">' + numbers[i] + '</button>');
}
Code that I have tried:
$('#buttons').append('<button class="boxes" id="' + numbers[i] + '" onclick="clicked(this);">' + numbers[i] + '</button>'); // made function called clicked with alert in return
$('button#-2).click(function () {
alert('Clicked on -2 box');
});
But it seems like none of this code seems to show me an alert for which box I clicked. Am I missing something?
Rather than relying on the ID for the boxes to know what their values are (which is bad because IDs are supposed to be unique), you can use the text inside of the button. If you’re not actually supposed to have that in their text (I assume this is a guessing game?), you can use a data attribute to assign them values: