user3503716
user3503716

Reputation: 17

simple javascript appendChild doesn't work

I'm new to web programming. I have tried to draw a table row with JavaScript but it's not working and I don't' know why.

here's the code

<div id="gameDiv"> </div>
<script type="text/javascript">
    public function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'
        for (j=0; j<8; j++) {
            var text = document.createTextNode(c++);
            var cell = startRow.insertCell(j);
            cell.appendChild(text);
        }
        document.getElementById("gameDiv").appendChild(table);
    }
    $(document).ready(function() {
        drawGame();
    };
</script>

Upvotes: 1

Views: 983

Answers (4)

Dog Ears
Dog Ears

Reputation: 10035

This should get rid of that NaN (Not a Number) nonsense.

<script>
        function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'.charCodeAt()
        for(j=0; j<8; j++){
            var text = document.createTextNode(String.fromCharCode(c++));
            var cell = startRow.insertCell(j);

            cell.appendChild(text);

        }
    document.getElementById("gameDiv").appendChild(table);

    }

    $(document).ready(function() {
    drawGame();

    });
</script>

Upvotes: 0

Yanaki
Yanaki

Reputation: 254

Here is kind of working variant http://jsbin.com/hisewamu/4/edit, "$" notion is part from jquery that you should include

Upvotes: 0

edwh
edwh

Reputation: 58

Well, you're getting an error because I think you might be getting your languages mixed up, there's no need to declare a function as public in javascript, it will give you an error.

The drawGame function can just be:

    function drawGame(){ 
        var table = document.createElement('table');
        table.setAttribute('style','float:left');
        var startRow = table.insertRow(0);
        var c = 'A'
        for(j=0; j<8; j++){
            var text = document.createTextNode(c++);
            var cell = startRow.insertCell(j);

            cell.appendChild(text);

        }
}

Upvotes: 0

Joeytje50
Joeytje50

Reputation: 19122

The problem is the fact you use public. Javascript doesn't have public or private, so putting that in front of your function declaration will cause errors. If you open up your console, you'll see an error like:

SyntaxError: Unexpected token function

So to fix this, simply remove the private modifier from your code.

Also, you seem to be missing a closing parenthesis at the end of your code. Instead, you should use this:

$(document).ready(function() {
    drawGame();
});

but that code could also be written much shorter:

$(drawGame);

Upvotes: 5

Related Questions