Kyle
Kyle

Reputation: 1183

Problems using x.length within for loop

I'm having problems trying to dynamically generate an HTML table based on input (column/row) values.

When I hardcode the values in the loop below (i.e. instead of using the prompt), it creates the correct number of cells. However, when using x.length within the loop, something isn't working correctly.

works correctly:

function createTable() {

    // declare variables
    var body = document.body,
        table = document.createElement('table');


    // Begin creating table
    // for each row
    for(var r = 0; r < 8; r++) {

        // create row
        var tr = table.insertRow();

        // for each column
        for(var c = 0; c < 8; c++) {

            // create column
            var td = tr.insertCell();
            td.appendChild(document.createTextNode('Cell'));

        }
    }

    // append table to body
    body.appendChild(table);
}

createTable();

does not create correct cells based on variable input

function createTable() {

    // declare variables
    var body = document.body,
        table = document.createElement('table'),
        rows = prompt("enter rows"),
        columns = prompt("enter columns");


    // Begin creating table
    // for each row
    for(var r = 0; r < rows.length; r++) {

        // create row
        var tr = table.insertRow();

        // for each column
        for(var c = 0; c < columns.length; c++) {

            // create column
            var td = tr.insertCell();
            td.appendChild(document.createTextNode('Cell'));

        }
    }

    // append table to body
    body.appendChild(table);
}

createTable();

Upvotes: 0

Views: 32

Answers (2)

Camilo Pereira
Camilo Pereira

Reputation: 1

Use parseInt(rows) and parseInt(columns). This functions return an integer but you must check if the input is really an string-represented integer value.

Upvotes: 0

Bergi
Bergi

Reputation: 664346

rows and columns are strings, that's the only reason why they have a .length. You seem to want to use them as parsed numbers, without any lengths:

var body = document.body,
    table = document.createElement('table'),
    rows = parseInt(prompt("enter rows"), 10),
    columns = parseInt(prompt("enter columns"), 10);

for (var r = 0; r < rows; r++) {
    var tr = table.insertRow();
    for (var c = 0; c < columns; c++) {
        var td = tr.insertCell();
        td.appendChild(document.createTextNode('Cell'));
    }
}
body.appendChild(table);

Upvotes: 3

Related Questions