Skip to content
Advertisement

Assigning values to html elements and reading it

I’m trying to make tic-tac-toe game, basing just on html, CSS and 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. Of course, this doesn’t work now, so can you advise 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;
}

Advertisement

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement