Home > Enterprise >  Java-script create columns and rows based on user input
Java-script create columns and rows based on user input

Time:09-21

This is a JavaScript homework question that has taken me far too long to search the web to figure out. Based on learning loops, while, do while, and for loops. I am to:

Prompt the user for a number of rows and a number of columns. Using the * output the * character in the row and column pattern requested by the user. If the user requests 2 rows and 2 columns you should output:

**

**>

Code thus far:

\\ var row = prompt("How many rows?") var column = prompt("How many columns?") \\

I would appreciate the guidance that could lead me to the answer.

CodePudding user response:

Given that you have mentioned the output is in the form of a table, we use two loops here. The first one is to append every row and the nested loop is to append every column. colData.innerHTML = "*" gives the value/pattern that's supposed to be included in each column.
In the html file, this entire table is appended into the element that has pattern as its ID attribute.

let table = document.createElement('table');
let tbody = document.createElement('tbody');

table.appendChild(tbody);
document.getElementById('pattern').appendChild(table);

var row = prompt("How many rows?");
var column = prompt("How many columns?");

for(let i = 0 ; i< row; i  ){
    let rowVal = document.createElement('tr');
    for(let j = 0; j< column; j  ){
        let colData = document.createElement('td');
        colData.innerHTML = "*";
        rowVal.appendChild(colData);
    }
    
    tbody.appendChild(rowVal);
}
  • Related