4

Working on a simple jquery tic-tac-toe project. I'm trying to iterate through the board and save the values of each cell in an array, but can't figure out how to access the text inside each td. I've tried .text() and .value() but both return undefined

index.html:

<html>
    <head>
        <title>jQuery Tic Tac Toe</title>
    </head>
    <body>
        <table border="1" cellpadding="40">
            <tr>
                <td data-x="0" data-y="0">Test</td>
                <td data-x="1" data-y="0"></td>
                <td data-x="2" data-y="0"></td>
            </tr>
            <tr>
                <td data-x="0" data-y="1"></td>
                <td data-x="1" data-y="1"></td>
                <td data-x="2" data-y="1"></td>
            </tr>
            <tr>
                <td data-x="0" data-y="2"></td>
                <td data-x="1" data-y="2"></td>
                <td data-x="2" data-y="2"></td>
            </tr>
        </table>
        <div id="games"></div>
        <div id="message"></div>
        <button id="save">Save Game</button>
        <button id="previous">Show Previous Games</button>
    </body>
</html>

tic-tac-toe.js:

function getBoard(){
    board = [];
    $.each($("td"), function(index, cell){
        board.push(cell); //Need to return contents of cell
    });
    alert(board);
}
Brian Menard
  • 41
  • 1
  • 1
  • 2

3 Answers3

5

Try this:-

Use this cell.innerHTML instead of cell

        function getBoard() {
            board = [];
            $.each($("td"), function (index, cell) {
                board.push(cell.innerHTML); //Need to return contents of cell
            });
            alert(board);
        }

Hope this will help you.

Sharique Ansari
  • 1,458
  • 1
  • 12
  • 22
3

You need to use .text()

 $.each("td", function(index, cell) {
   board.push($(cell).text()); //Need to return contents of cell
 });
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
2

You can try this way, explained on this link: https://stackoverflow.com/a/3072366/6356627

function GetCellValues() {
        var table = document.getElementById('mytable');
        for (var r = 0, n = table.rows.length; r < n; r++) {
            for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
                alert(table.rows[r].cells[c].innerHTML);
            }
        }
    }
Community
  • 1
  • 1