javascriptjqueryhtml

How to create board NxN using JavaScript and jQuery


I am trying to create board game (like chess board game) with JavaScript.

When I tried to do it this is what happened:

enter image description here

The <tr> got closed immediately with </tr>, same thing with <table> </table>
I tried to replace the append() method with appendTo() or add() but it didn't help.

This is my code:

var boardSize = 5;

$(function() { //on load
    printBoard(boardSize);
});

function printBoard(i_BoardSize) {
    var maxRow = parseInt(i_BoardSize);
    var maxCol = parseInt(i_BoardSize);
    var num = 1;

    $("#board").append("<table oncontextmenu=\"return false\">");
    for(var row = maxRow - 1; row >= 0 ; row--) { 
        $("#board").append("<tr>");
        for(var col = 0; col < maxCol ; col++) {
            $("#board").append("<td>" + num + "</td>");
            num++;
        }
        $("#board").append("</tr>");
    }
    $("#board").append("</table>");
}
td {
    width: 32px;
    height: 32px;
    cursor: pointer;
    text-align: center;
    border: 2px solid blue;
}

.redborder {
    background-color: red;
    color: white;
}

.blueborder {
    background-color: blue;
    color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> <center><h3><font size="20" color="black"> Board Game</font></h3></center></p>
<div>
    <div id="board">
        <div class="cell">
        </div>
    </div>
</div>


Solution

  • This happens because jQuery append() method not supporting only closing tags and trying to close tags if they wasn't closed in provided param. To solve this you need to assign your append() result to some variable, for example:

    var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");
    

    and then append your rows to this var:

    var myRow = $("<tr></tr>").appendTo( myTable );
    

    Same with columns:

    myRow.append("<td>" + num + "</td>");
    

    By using appendTo method you will be able to get newly created elements.

    So your final code should look like:

    var boardSize = 5;
    
    $(function() { //on load
        printBoard(boardSize);
    });
    
    function printBoard(i_BoardSize) {
        var maxRow = parseInt(i_BoardSize);
        var maxCol = parseInt(i_BoardSize);
        var num = 1;
    
        var myTable = $("<table oncontextmenu=\"return false\"></table>").appendTo("#board");
        for (var row = maxRow - 1; row >= 0; row--) {
            var myRow = $("<tr></tr>").appendTo(myTable);
            for (var col = 0; col < maxCol; col++) {
                myRow.append("<td>" + num + "</td>");
                num++;
            }
        }
    }