Im beginner. I use a HTML table code like this (see below) for Unicode print using char's Decimal values:
<table border="1">
<tr><td>1</td><td></td>
<tr><td>2</td><td></td>
<tr><td>3</td><td></td>
...
<!-- last one: thousandth row -->
<tr><td>1000</td><td>Ϩ</td>
</table>
Is it possible to convert this code into an auto-generated table as follows using JavaScript or JQuery?
<table border="1">
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
...
<!-- thousandth row -->
<tr><td>rowNumber</td><td>innerHTML = "\u0026\u0023 + rowNumber + \u003B";</td>
</table>
You can start by creating a record-generating function.
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
Then you can generate the JSON.
generateRecords(i => {
return {
dec: i,
entity: '&#' + i + ';',
rendered: '&#' + i + ';'
}
}, 1000);
Finally, all you need to do is render the JSON to a table.
Example
(function($) {
$.fn.attrs = function(attrs) {
var $self = this;
if (attrs != null) {
$.each(attrs, function(attr, value) {
$self.attr(attr, value);
});
return $self;
} else {
var result = {};
$.each(this[0].attributes, function(index, attribute) {
result[attribute.name] = attribute.value;
});
return result;
}
};
$.fn.tableFromJson = function(data, attrs, indexField) {
return this.replaceWith($.tableFromJson.apply(this, arguments));
};
$.tableFromJson = function(data, attrs, indexField) {
var fields = Object.keys(data[0]);
if (indexField != null) fields.unshift(indexField);
return $('<table>')
.append($('<thead>').append($('<tr>').append(fields
.map(field => $('<th>').text(field)))))
.append($('<tbody>').append(data
.map((rec, row) => $('<tr>').append(fields
.map((field, col) => $('<td>').html(field === indexField ? (row + 1) : rec[field])))))).attrs(attrs);
};
})(jQuery);
function generateRecords(recordFn, limit) {
var records = [];
for (var i = 0; i < limit; i++) {
records.push(recordFn.call(null, i, records));
}
return records;
}
$('.column:nth-child(1) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
entity: '&#' + i + ';',
rendered: '&#' + i + ';'
}
}, 1000), $('.column:nth-child(1) .result').attrs());
$('.column:nth-child(2) .result').tableFromJson(generateRecords(i => {
return {
dec: i,
rendered: '\u0026\u0023' + i + '\u003B'
}
}, 1000), $('.column:nth-child(2) .result').attrs());
.container { width: 100%; }
.column { display: inline-block; width: 49%; }
table.result {
margin-bottom: 0.5em;
}
table.result,
table.result th,
table.result td {
border: 1px solid black;
border-collapse: collapse;
}
table.result th,
table.result td {
padding: 0.25em;
}
table.result tbody tr td {
text-align: center;
}
table.result thead tr {
background: #BBB;
}
table.result tbody tr:nth-child(even) {
background: #EEE;
}
table.result tbody tr:nth-child(odd) {
background: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="column">
<table class="result"></table>
</div>
<div class="column">
<table class="result"></table>
</div>
</div>
You can try with this
var table = $('<table>').prop('border', 1);
for(i=0; i<1000; i++){
var row = $('<tr><td>' + i + '</td><td>&#'++'</td></tr>'
table.append(row);
}
$('#mytable').append(table);
Yes, Thats possible using javascript/JQuery.For that you need to use proper js code. Below is the sample code that can help you to create table and row,data using jquery.
Below code is responsible to create table tag
$('.class-name').append('<table border="3"></table>');
This will create table element inside your HTML having classname as .class-name.
Once the table tag is created you can create table row and data element as below.
$("table").append(createRow());
function createRow(){
var firstVal = '1st val';
var secondVal = '2nd val';
var tr = '<tr>' ;
tr += '<td>' + firstVal + '</td>';
tr += '<td>' + secondVal + '</td>';
tr +='</tr>';
return tr;
}
This code will generate the table row and will print the table data as st val and 2nd val.
Hope this code may help you
Related
Using a javascript function
function initializeUserTable(tableHeaders , tableData ) {
// I want to set table headers and table data
}
var tableHeaders = "ID,USERNAME,STATUS,LOGIN";
var tableData = "1,ABC,ACTIVE,N,2,DEF,INACTIVE,Y,3,XYZ,ACTIVE,Y";
want to set the tableHeaders as a header and data as a tableData, so the table looks like
I hope this is help you
var table = document.getElementsByTagName("table")[0];
var ths = ["ID","USERNAME","STATUS","LOGIN"];
var tds = [["1","ABC","ACTIVE","N"],["2","DEF","INACTIVE","Y"],["3","XYZ","ACTIVE","Y"]];
let tr = document.createElement("tr");
function initializeUserTable(tableHeaders , tableData ){
for(let i=0;i<ths.length;i++){
for(let j=0;j<tableHeaders.length;j++){
if(i==0){
let th = document.createElement("th");
th.innerHTML=tableHeaders[j];
if(j==0){
tr.appendChild(th);
}
tr.appendChild(th);
}
else{
let td = document.createElement("td");
td.innerHTML=tableData[i-1][j];
tr.appendChild(td);
}
}
table.insertAdjacentElement("beforeend",tr);
tr = document.createElement("tr");
}
}
initializeUserTable(ths,tds);
table{
border-collapse: collapse;
}
table,th, td {
border:2px solid black;
width:50%;
height:20px;
text-align: center;
}
th{
background: lightgray;
}
<!DOCTYPE html>
<html>
<head>
<title>tableData</title>
</head>
<body>
<table>
</table>
</body>
</html>
you can use :
yourstring.split(",") to transform your data as array
table.insertRow to insert new row in a table tag
row.insertCell to insert new cell in table tag
var tableHeaders = "ID,USERNAME,STATUS,LOGIN";
var tableData = "1,ABC,ACTIVE,N,2,DEF,INACTIVE,Y,3,XYZ,ACTIVE,Y";
function insertRow(table) {
if (!table.dataset.number) {
table.dataset.number = 0;
}
var rowNumber = parseInt(table.dataset.number);
table.dataset.number = rowNumber + 1;
return table.insertRow(rowNumber);
}
function insertCell(row) {
if (!row.dataset.number) {
row.dataset.number = 0;
}
var cellNumber = parseInt(row.dataset.number);
row.dataset.number = cellNumber + 1;
return row.insertCell(cellNumber);
}
function initializeUserTable(tableHeaders, tableData) {
var headers = tableHeaders.split(",");
var datas = tableData.split(",");
var table = document.getElementById('my-table');
var row = insertRow(table);
let cell;
headers.forEach(header => {
cell = insertCell(row);
cell.outerHTML = `<th>${header}</th>`;
});
row = insertRow(table);
datas.forEach(data => {
cell = insertCell(row);
cell.innerHTML = data;
if (parseInt(row.dataset.number) === headers.length) {
row = insertRow(table);
}
});
}
initializeUserTable(tableHeaders, tableData);
table,th, td {
border:1px solid #ddd;
padding:5px;
text-align: center;
}
table {
border-collapse: collapse;
}
th {
background: #efefef;
}
<table id="my-table"><table>
I am working with HTML tables and need to achieve color change in a certain way.
My desired result is as described below.
Lower figure shows that assume current state is upper figure,then cell 1 is clicked,upper figure becomes like lower figure.
I would like to selectfirstelement,and then add 'aqua' class after5cells including first cell.
I achieved to select first cells among these clicked cells,But I couldn't figure out how to detect after 5 cells which has 'class'.
If someone has opinion,please let me know
Thanks
$("td").click(function() {
$(this).addClass("red");
$("td.aqua").removeClass("aqua");
$("td.red").first().addClass("aqua");
});
td {
transition-duration: 0.5s;
border: solid black 1px;
padding: 5px;
cursor:pointer;
}
table {
border-collapse: collapse;
}
.red {
background-color:red;}
.aqua{
background-color:aqua;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
for (let w = 0; w < 5; w++) {
html += '<tr>';
for (let d = 0; d < 10; d++) {
i=i+1;
html += '<td>'+ i+'</td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
</script>
I'm not 100% sure I understand correctly what you need to do, but this will color the clicked cell in aqua and the following 5 cells in red. Even if it's not exactly what you need, it should guide you in the right direction.
$('body').on('click', "td", function() {
let _this = this;
let _index = -1;
$(this).parents('table').find('td').each(function(i, el){
if(el == _this){
_index = i;
}
if (_index > -1 && i > _index && i < (_index + 6)){
console.log(i);
$(el).addClass('red');
}
});
$(this).addClass("aqua");
});
On a logical level you need to loop through all your td elements and detect which one of them has been clicked, get the index if it and then add the class red to the following 5 elements. Apply class aqua to the clicked one either at the end or at the beginning.
Does this what you want?
$("table").on("click", "td", function(ev) {
$(this).removeClass("aqua").addClass("red");
let nextRowIdx = this.parentNode.rowIndex,
nextCellIdx = this.cellIndex + 5;
if (nextCellIdx >=10) {
nextRowIdx += 1;
nextCellIdx -= 10;
}
try {
let tbl = this.parentNode.parentNode,
cell = tbl.children[nextRowIdx].children[nextCellIdx];
$(cell).removeClass("red").addClass("aqua");
} catch (err) {
}
});
td {
transition-duration: 0.5s;
border: solid black 1px;
padding: 5px;
cursor:pointer;
}
table {
border-collapse: collapse;
}
.red {
background-color:red;}
.aqua{
background-color:aqua;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
for (let w = 0; w < 5; w++) {
html += '<tr>';
for (let d = 0; d < 10; d++) {
i=i+1;
html += '<td>'+ i+'</td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
</script>
I have this code below that popups the cell value whenever the user clicks a specific cell.
What I'm currently trying to do is when the user clicks a cell i want that cell value to be appended to another column. I tried using the push method but it doesn't seem to be working. I'm not sure if I'm doing it the wrong way
JFiddle
HTML:
<table id="fruitsTable" class="fruitstableroni skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
JavaScript:
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
obj[key2].push(this); //Trying to push it to the second column.
console.log(this);
};
}
}
function getval(cel) {
//console.log(cel.innerHTML);
}
var obj = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj[key3] = ['Soursop', 'Papaya', 'Pineapple', 'Melon'];
var myArray3 = [];
myArray3.push(obj);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length); // find the longest
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") + // ternary - instead of using if/else
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsTableClass thead').html($header);
$('.fruitsTableClass tbody').html(bodyString);
var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function() {
getval(this);
obj[key2].push(this);
};
}
}
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<table id="fruitsTable" class="fruitsTableClass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
Restructure your code to have a method to redraw UI and to enable event listeners:
function redraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length) // find the longest
$header.append($('<th/>').text(key + ': ' + values.length))
})
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') + // ternary - instead of using if/else
'</td>'
})
bodyString += '</tr>'
}
$('.fruitsTableClass thead').html($header)
$('.fruitsTableClass tbody').html(bodyString)
}
function listener (obj) {
tbl = document.getElementById('fruitsTable')
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this)
obj[key2].push(this.innerHTML)
redraw(obj)
listener(obj)
};
}
}
}
function getval (cel) {
alert(cel.innerHTML)
}
redraw(obj)
listener(obj)
JSFiddle - https://jsfiddle.net/gnm8wv5f/
To add rows or cells to a table, you should use the methods insertRow() and insertCell().
Example, if you want to add a cell at the beginning of a row (from w3schools):
var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";
Or, to insert at the end:
var x = row.insertCell(row.cells.length);
Using cells.length you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.
More info in: w3 | MDN
Try this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var daraArray=[];
$(document).ready(function(){
$(".classTd").click(function(){
//console.log($(this).html());
daraArray.push($(this).html());
console.log(daraArray);
});
});
</script>
<style type="text/css">
.classTd{
text-align: center;
}
</style>
</head>
<table id="fruitsTable" class="fruitstableroni skillsTable class" border="1">
<thead></thead>
<tbody>
<tr>
<td class="classTd" width="10%">1</td>
<td class="classTd" width="10%">2</td>
<td class="classTd" width="10%">3</td>
</tr>
<tr>
<td class="classTd" width="10%">4</td>
<td class="classTd" width="10%">5</td>
<td class="classTd" width="10%">6</td>
</tr>
<tr>
<td class="classTd" width="10%">7</td>
<td class="classTd" width="10%">8</td>
<td class="classTd" width="10%">9</td>
</tr>
</tbody>
</table>
</html>
The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.
I have this code below that prints the value of random fruits table whenever i click the cell value. The problem is i'm trying to create a function that allows me to move the value of random fruits table into the red fruits table by clicking on for example kiwi and it will move into the red fruits table and also i want to be able to move back that value i moved into red fruits table back to the random fruits table. I tried to do it using the array push method but it only copies the value into the other table and not completely move it. Is there any easy way to do this any suggestion would be greatly appreciated thanks!
var obj = {};
var obj2 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum'];
var myArray3 = [];
myArray3.push(obj2);
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length);
$header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) {
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") +
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsclass thead').html($header);
$('.fruitsclass tbody').html(bodyString);
var bodyString = '';
var headString = '';
$.each(obj2[key3], function(index) {
bodyString += ('<tr><td>' + obj2[key3][index] + '</td></tr>');
});
headString += ('<tr><th>' + 'Random Fruits' + '</th></tr>');
$('.fruityclass tbody').html(bodyString);
$('.fruityclass thead').html(headString);
$(document).ready(function() {
$("#fruityid td").click(function() {
getval(this);
});
});
function getval(cel) {
alert(cel.innerHTML);
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
}
table {
float: left;
border-collapse: collapse;
width: 70%
}
td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
th {
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
div {
margin-bottom: 50px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table id="fruityid" class="fruityclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
Working on top of your code, changed listener function to remove the node:
function listener(obj) {
tbl = document.getElementById("fruitsTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this);
data = this.innerHTML;
k1 = Object.keys(obj).find(k => obj[k].indexOf(data) >= 0 )
if (k1 != 'Random Fruits') {
key = 'Random Fruits'
} else {
key = 'Red Fruits';
}
index = obj[k1].indexOf(data);
obj[k1].splice(index, 1);
obj[key].push(data);
redraw(obj);
listener(obj);
};
}
}
}
It finds the relevant key and removes the element from that array, and pushes that into k2. Once done, it redraws the UI.
Fiddle - https://jsfiddle.net/wqzsn7ou/
Please explain why the code I borrowed from another SO question produces inconsistent results. The program accepts 2 inputs, rows and columns. It should then generate a table with the exact amount of table rows and table columns that was input. However, the first row seems to multiply out the cells and decrease each row until the final row actually renders what every other row should be.
Also, I noticed that when I move line 25 inside of the inner while loop, that a table that is akin to a pyramid is generated (which is cool) but I cannot explain what it is doing.
$("<tr class='tableRow'>").appendTo('table#container');
So with that said, please help me generate a table that will evenly render rows and columns when the input is equal.
Note: Entering 1 for rows and 1 for columns does return the intended result, but that is the only scenario where it "works". Entering 2 for rows and 2 for columns, produces unintended results.
Sandbox Fiddle
//Table Generator
var c = 10; //parseInt(prompt("Enter column "), 10);
var r = 10; //parseInt(prompt("Enter row "), 10);
var cTmp = c;
var rTmp = r;
function rowLoop() {
$('tr.tableRow').each(function(index) {
var trFound = $("tr.tableRow:eq(" + index + ")");
var rowNum = parseInt(($("tr.tableRow:eq(" + index + ")").index()), 10);
var tdAdd = "<td>test</td>";
if ($(this).index() === rowNum) {
trFound.append(tdAdd);
console.log("Add a TD");
console.log(rowNum + "=" + $(this).index());
console.log(rowNum + "=" + $(this).index());
} else {
console.log(rowNum + "<>" + $(this).index());
console.log(rowNum + "<>" + $(this).index());
}
});
}
while (0 < rTmp) {
cTmp = c;
$("<tr class='tableRow'>").appendTo('table#container');
while (0 < cTmp) {
rowLoop();
cTmp--;
}
document.getElementById("container").innerHTML = document.getElementById("container").innerHTML + "</tr>";
rTmp--;
}
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id='container'></table>
Instead of using a while-loop why don't you just use a simple nested for-loop? This will make this task much easier to read and comprehend.
//Table Generator
var cols = 10; //parseInt(prompt("Enter column "), 10);
var rows = 10; //parseInt(prompt("Enter row "), 10);
generateTable('container', rows, cols, 'test');
function generateTable(id, rows, cols, fill) {
var elTable = document.getElementById(id);
createRows(elTable, rows, cols, fill);
}
function createRows(elTable, rows, cols, fill) {
for (var row = 0; row < rows; row++) {
elTable.appendChild(createRow(row, cols, fill));
}
}
function createRow(row, cols, fill) {
var elRow = document.createElement('tr');
elRow.className = 'tableRow';
createCols(elRow, row, cols, fill);
return elRow;
}
function createCols(elRow, row, cols, fill) {
for (var col = 0; col < cols; col++) {
elRow.appendChild(createCol(row, col, fill));
}
}
function createCol(row, col, fill) {
var elCol = document.createElement('td');
elCol.innerHTML = fill || row + 'x' + col;
return elCol;
}
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='container'></table>
jQuery Plugin
You can skip the loop altogether and use a range-map. You can actually define an array using:
Array.apply(null, Array(n)) // Where n is an integer greater than 0
You can then map each item in the array to either a function or the current index in the map function.
map(function(_, idx) {
// Return the current index in the map's "loop" callback.
if (val == null) return idx;
// Execute the value as a function; pass index as 1st param.
if (isFunction(val)) return val.call(null, idx);
// Return the value as an (assumed) scalar value.
return val;
});
Here is a jQuery plugin to generate rows and columns using the explained trick above to generate an array at a desired size with an option default value.
//Table Generator
(function($) {
$.fn.generateTable = function(options) {
var defaults = {
rows: 0,
cols: 0,
fill: function(row, col) {
return row + 'x' + col;
}
};
var opts = $.extend(defaults, options);
function fillArray(n, val) {
return Array.apply(null, Array(n)).map(function(_, idx) {
return val == null ? idx : isFunction(val) ? val.call(null, idx) : val;
});
}
function isFunction(value) {
return typeof value == 'function';
}
return $(this).append(fillArray(opts.rows, function(row) {
return $('<tr>', {
class: 'tableRow'
}).append(fillArray(opts.cols, function(col) {
return $('<td>', {
text: isFunction(opts.fill) ? opts.fill.call(null, row, col) : opts.fill
});
}));
}));
};
}(jQuery));
$(function() {
$('#container').generateTable({
rows: 10, //parseInt(prompt("Enter row count"), 10)
cols: 10, //parseInt(prompt("Enter column count"), 10)
fill: 'test'
});
});
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='container'></table>
Stages of Development
Below, you will see how each successive block of code has evolved from its predecessor.
I. Vanilla JavaScript translated to jQuery
//Table Generator
var cols = 10; //parseInt(prompt("Enter column "), 10);
var rows = 10; //parseInt(prompt("Enter row "), 10);
generateTable('#container', rows, cols, 'test');
function generateTable(selector, rows, cols, fill) {
var $el = $(selector)
createRows($el, rows, cols, fill);
}
function createRows($table, rows, cols, fill) {
for (var row = 0; row < rows; row++) {
$table.append(createRow(row, cols, fill));
}
}
function createRow(row, cols, fill) {
var $row = $('<tr>', {
class: 'tableRow'
});
createCols($row, row, cols, fill);
return $row;
}
function createCols($row, row, cols, fill) {
for (var col = 0; col < cols; col++) {
$row.append(createCol(row, col, fill));
}
}
function createCol(row, col, fill) {
return $('<td>', {
text: fill || row + 'x' + col
});
}
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='container'></table>
II. Simple jQuery Plugin
//Table Generator
(function($) {
$.fn.generateTable = function(options) {
var $table = $(this);
_createRows($table, options.rows, options.cols, options.fill);
};
_createRows = function($table, rows, cols, fill) {
for (var row = 0; row < rows; row++) {
$table.append(_createRow(row, cols, fill));
}
};
_createRow = function(row, cols, fill) {
var $row = $('<tr>', {
class: 'tableRow'
});
_createCols($row, row, cols, fill);
return $row;
};
_createCols = function($row, row, cols, fill) {
for (var col = 0; col < cols; col++) {
$row.append(_createCol(row, col, fill));
}
};
_createCol = function(row, col, fill) {
return $('<td>', {
text: fill || row + 'x' + col
});
};
}(jQuery));
var cols = 10; //parseInt(prompt("Enter column "), 10);
var rows = 10; //parseInt(prompt("Enter row "), 10);
$(function() {
$('#container').generateTable({
rows: rows,
cols: cols,
fill: 'test'
});
});
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='container'></table>
III. Advanced jQuery Plugin
//Table Generator
(function($) {
$.fn.generateTable = function(options) {
$(this).append(_fillArray(options.rows, function(row) {
return $('<tr>', {
class: 'tableRow'
}).append(_fillArray(options.cols, function(col) {
return $('<td>', {
text: options.fill || row + 'x' + col
});
}));
}));
};
function _fillArray(n, defaultValue) {
return Array.apply(null, Array(n)).map(function(val, idx) {
if (defaultValue === undefined) return idx;
if (typeof defaultValue == 'function') return defaultValue.call(null, idx);
return defaultValue;
});
}
}(jQuery));
var colCount = 10; //parseInt(prompt("Enter column "), 10);
var rowCount = 10; //parseInt(prompt("Enter row "), 10);
$(function() {
$('#container').generateTable({
rows: rowCount,
cols: colCount,
fill: 'test'
});
});
table {
border-collapse: collapse;
border: solid 1px #ACE;
}
tr {
height: 15px;
}
td {
border: solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='container'></table>
Your problem likely stems from the fact that within each rowLoop() execution, you are using this as selector for iteration:
$('tr.tableRow')
This will grab all rows that are currently in DOM for iteration, not just the current row you are working on.
A few options:
Build a single row object with X number of columns first, then make clones of it and append to table for Y number of rows.
Build Y empty TR's first, then iterate over each TR, appending X TD's.