Returning value from JS function

Hi,
I am just starting to work with functions in Javascript. I can’t figure out why the following function rand() will not return a random number when called. The random number is used to set the background of the table cells.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>
            Generate table
        </title>
    </head>
    <body>
        <input type="button" value="Generate table" onclick="generate_table()">
        <script language="javascript">
            function generate_table(){
                var body = document.getElementsByTagName("body")[0];
                var tbl = document.createElement("table");
                var tblBody = document.createElement("tbody");
                for(var i = 0; i < 20; i++){
                    var row = document.createElement("tr");
                    for(var j = 0; j < 20; j++);
                        var cell = document.createElement("td");
                        function rand(){
                            var r = Math.floor(Math.random()*255);
                            return r;
                        }
                        cell.style.background = "rgb(" + rand() + "," + rand() + "," + rand()")";
                        cell.style.width = "50px";
                        cell.style.height = "50px";
                        cell.setAttribute("align", "center");
                        var cellText = document.createTextNode(" ");
                        cell.appendChild(cellText);
                        row.appendChild(cell);
                    }
                    tblBody.appendChild(row);
                }
                tbl.appendChild(tblBody);
                body.appendChild(tbl);
            }
        </script>            
    </body>
</html>

Thanks,
Shane

You have two errors.

cell.style.background = "rgb(" + rand() + "," + rand() + "," + rand()")";

Look at the last rand(). You don’t + to the string. It should be this

cell.style.background = "rgb(" + rand() + "," + rand() + "," + rand()+")";

Next, you don’t give this for loop an opening bracket. Instead you give it a semi colon.

for(var j = 0; j < 20; j++);

Make it this.

for(var j = 0; j < 20; j++) {

When I do these two changes, I get the following.
http://codepen.io/ryanreese09/pen/rVaWeB

Ah yes! Stupid little things.
Thanks works great now.
I like the way you can but the website in a post here.
Thanks,
Shane

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.