I need help reducing my JavaScript code down to between 4 - 7 lines of code. The idea of this program is to include the number 1-9 in a 3x3 table. I have included both my JavaScript code and the HTML code that creates the table. The javascript code that i have included does work, however i have been told that it is not the correct way to achieve this.

Here is the HTML for my table:

<table border="1" cellpadding="5">
    <tbody>
        <tr>
            <td id="cell1">1</td>
            <td id="cell2">2</td>
            <td id="cell3">3</td>
        </tr>
        <tr>
            <td id="cell4">4</td>
            <td id="cell5">5</td>
            <td id="cell6">6</td>
        </tr>
        <tr>
            <td id="cell7">7</td>
            <td id="cell8">8</td>
            <td id="cell9">9</td>
        </tr>
    </tbody>
</table>

Here is the JavaScript code i am using in conjunction with the above HTML to put numbers in order 1 - 9 within it, however i have been told this is wrong and it can be done using a loop and in 7 lines of code or less (between 4 and 7 lines of code):

document.getElementById("cell1").innerHTML = "1";
document.getElementById("cell2").innerHTML = "2";
document.getElementById("cell3").innerHTML = "3";
document.getElementById("cell4").innerHTML = "4";
document.getElementById("cell5").innerHTML = "5";
document.getElementById("cell6").innerHTML = "6";
document.getElementById("cell7").innerHTML = "7";
document.getElementById("cell8").innerHTML = "8";
document.getElementById("cell9").innerHTML = "9";

I assume i will need to create a for loop that adds these numbers into the table concatenating them into some form of string. But i have no idea as to how i will be able to achieve this?? This is the only other thing i have had troubles with. I think the JavaScript i have supplied is fine and it works too, but i am told this is not the best way to do this. If anyone can help that would be great, Thanks

Recommended Answers

All 2 Replies

Do you want generate the entire table (document.createElement) using a loop and assign innerHTML, or just assign the innerHTML value using a loop?

I had answered this in your other post, just in case you didnt see it...

Sure, although I'd suggest starting a new thread next time.

Your approach is not optimized because what if you had 100 cells to fill. For the table...you are correct about using a loop. One option is that you can fill in the data using a "For" loop. Here is an example of how you would go about it..

<script>
    for (var x = 1; x < 10; x++) {
        document.getElementById("cell" + x).innerHTML = x;
    }
</script>

You can build the HTML table in the same manner if you want to do it via JavaScript.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.