My goal is to create a 2-Dimensional array if text based (numerical) inputs. I want to use the same input type box that is used in HTML, like:
<input type="text">
The amount of rows and cols would be based off another input in the HTML document. Here's what I have so far:
var rows = document.getElementById("rows");
var cols = document.getElementById("cols");
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
//I don't know what to do here
}
}
What do I put in the nested for loops to get a multidimensional array of inputs listed? Here is an example of what I am trying to get the thing to look like. The user will be able to click each element and be able to enter a number.
function createTable() { var table = document.createElement('table'); var rows = +document.getElementById('rows').value; var cols = +document.getElementById('cols').value; for(var r=0; r<rows; r++) { var tr = document.createElement('tr'); table.appendChild(tr); for(var c=0; c<cols; c++) { var td = document.createElement('td'); tr.appendChild(td); var inp = document.createElement('input'); inp.setAttribute('type','text'); td.appendChild(inp); } } var container = document.getElementById('input_container'); container.innerHTML = ''; container.appendChild(table); }
td>input { width: 30px; height: 30px; padding: 5px; font-size: 20px; }
Rows : <input type="text" id="rows" value="3"> Cols : <input type="text" id="cols" value="8"> <button onclick="createTable();">Create</button> <div id="input_container"></div>
var rows = document.getElementById("rows");
var cols = document.getElementById("cols");
var multi = []; // the multidimensional array of inputs
for(var i = 0; i < rows; i++){
var sub = []; // create a new sub-array for each row
for(var j = 0; j < cols; j++){ // fill the sub array
var input = document.createElement("INPUT"); // create an new input
input.setAttribute("type", "text");
sub.push(input); // push it into the sub array
}
multi.push(sub); // push the sub array into the multi array
}
Then multi
will be somthing like this:
[
[input, input, input, ..., input],
[input, input, input, ..., input],
...
[input, input, input, ..., input]
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.