JSFiddle - React, Tailwind, and code Playground
by mori57
HTML
<label for="rows">Rows: <input id="rows" type="text"/></label>
<label for="columns">Columns: <input id="columns" type="text"/></label>
<button id="go">Run</button>
<div id="boxs"></div>
CSS
/* Float me text boxes! */
#boxs input[type='text'] {
float:left;
display:block;
width: 50px;
margin: 0 3px 3px 0;
}
/* use this to tell this input box to start a new row */
#boxs input[type=text].rowstart {
clear:both;
}
JavaScript
function grid() {
// first, let's cache these items ... getElementById is expensive
var row = document.getElementById("rows");
var column = document.getElementById("columns");
// Also, did you realize you weren't actually adding these boxes to the
// boxs element? Cache a reference to that div, here, so you can hit it quickly
// in the append phase...
var boxs = document.getElementById("boxs");
rows = parseInt(row.value);
columns = parseInt(column.value);
// create a cached template of the input box that you'll reuse
// because createElement is also expensive
// ... as an aside, .innerHTML is the cheapest option, but I'm trying
// to keep things semi-simple in this example
var boxTemplate = document.createElement("input");
boxTemplate.setAttribute("type", "text");
boxTemplate.setAttribute("size", "5");
// You really don't need to specify style on the element itself...
// leave that to your css, or you'll have to touch your JS logic every time
// you need to change the spacing
// Make a cached template of your disabled-state boxes, too, why not?
var outBoxTemplate = boxTemplate.cloneNode();
outBoxTemplate.setAttribute("disabled", "disabled");
for (var x = 0; x <= rows; x++) {
// since we know what should be the last row, create
// a boolean to track that state
var outRow = (x == rows);
for (var y = 0; y <= columns; y++) {
// get a new box instance by cloning the node
var box = boxTemplate.cloneNode();
box.setAttribute("id", "tb" + x + y);
// if this is the first box, give it the class of rowstart
// to force it to go to a new line as its CSS spec states
if(y == 0) {
...