Here is a working version:
<style>
.row { width: 100%; clear: both; text-align: center; }
.col { display: inline-block; min-height: 20px; min-width: 20px; padding: 8px 10px; background-color: #ededed; margin: 1px; }
.col:hover { background-color: #333333; color: #ffffff; }
</style>
<input type="button" onClick="genDivs(6);" value="click me" />
<div id="target"></div>
<script language="javascript">
function genDivs(rows,cols){
var e = document.getElementById("target");
cols = cols || rows;
for(var r = 0; r < rows; r++) {
var row = document.createElement("div");
row.className = "row";
for(var c = 0; c < cols; c++) {
var col = document.createElement("div");
col.className = "col";
col.innerHTML = (r * rows) + c;
col.innerHTML = getElement();
row.appendChild(col);
}
e.appendChild(row);
}
}
function getElement(){
var elements = [
"A",
"B",
"C"
]
return elements[Math.floor(Math.random() * (elements.length))];
}
</script>
This is easier with jQuery. I used vanilla Javacript. I'd usually put the onclick in the javascript, but I left it as is for you.
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/chLLg4rr/
Hope this helps.
Per request, I've made a jQuery version. I also used lodash to make this more efficient(lodash comes in really handy). And I've more properly separated the script, the html and the styles - these should each go in a different file. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/btb9vp26/
script:
function grid(rows,cols,target){
cols = cols || rows;
target = target || "grid";
var gridDiv = $("." + target);
gridDiv.html(''); // clear grid to reload
_.times(rows, function() {
gridDiv
.each(function(){ // allows multiple grids
$(this).append(addRows(rows,cols));
});
});
};
function addRows(rows,cols){
return $("<div />")
.addClass("row")
.html(
addCols(cols)
);
};
function addCols(cols){
return _.times(cols, function() {
return $("<div />")
.addClass("col")
.html( getElement() );
});
};
function getElement(){
var elements = [
"A",
"B",
"C"
];
return _.sample(elements);
};
$(".js-grid").click( function(){ grid(6,10) } );
$(".js-grid2").click( function(){ grid(3,5,'grid2') } );
html:
<button type="btn btn-info" class="js-grid">Click me</button>
<button type="btn btn-info" class="js-grid">Or me</button>
<button type="btn btn-info" class="js-grid2">Grid 2</button>
<div class="grid"></div><div class="grid2"></div>
<div class="grid"></div>
styles:
.row { width: 100%; clear: both; text-align: center; }
.col { display: inline-block; min-height: 20px; min-width: 20px; padding: 8px 10px; background-color: #ededed; margin: 1px; }
.col:hover { background-color: #333333; color: #ffffff; }
.grid, .grid2 { margin-bottom: 10px; }