Dan Zawadzki Dan Zawadzki - 16 days ago 7
Javascript Question

Assigning values to html elements and reading it

i'm trying to make tic tac toe game, basing just on html,css,pure js. I have already base of game (there is one bug), but i have problem to detect once someone wins. I've decided to use MagicSquare algorithm, but i don't have idea how to attach value to each td element. Here you can find, what i have at this moment. I'm trying to make something like

player += Number(target.value);
and once one of the players collect 15, then i stop game and display message. Ofc, this doesn't work now, so can you advice me some good idea how to assign values with td elements and later read it via js, once player generate click event?

index.html

<table class="gameArea" onclick="myFunction(event)">
<tbody>
<tr>
<td value=4></td>
<td value="9"></td>
<td value="2"></td>
</tr>
<tr>
<td value="3"></td>
<td value="5"></td>
<td value="7"></td>
</tr>
<tr>
<td value="8"></td>
<td value="1"></td>
<td value="6"></td>
</tr>
</tbody>
</table>


script.js

var player1 = 0,
player2 = 0,
round = 0;

function myFunction(event) {
var target = event.target;
//target.className += "x";

if(hasClass(target, "x") || hasClass(target, "y") ){
alert("Taken");
return;
}

if(round === 1){
target.className += "x";
player1 += Number(target.value);
round = 0;
console.log(target.value);
} else {
target.className += "y";
round = 1;
player2 += Number(target.value);
console.log("Player 2: " + player2);
}

console.log(round);
}

function hasClass( elem, klass ) {
return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}

Answer

Change your HTML to use data attributes, like so:

<td data-value="3"></td>

You can then read the value, like so:

player1 += parseInt(target.dataset.value, 10);

More info on MDN here.