Generate table based on number of rows, columns in jquery - javascript

How do I generate a table in jQuery based on a given number of rows and columns?

You can use nested for loops, create elements and append them to one another. Here's a very simple example that demonstrates creating DOM elements, and appending them.
You'll notice that the $('<tag>') syntax will create an element, and you can use the appendTo method to, well, do exactly that. Then, you can add the resulting table to the DOM.
var rows = 5; //here's your number of rows and columns
var cols = 5;
var table = $('<table><tbody>');
for(var r = 0; r < rows; r++)
{
var tr = $('<tr>');
for (var c = 0; c < cols; c++)
$('<td>some value</td>').appendTo(tr); //fill in your cells with something meaningful here
tr.appendTo(table);
}
table.appendTo('body'); //Add your resulting table to the DOM, I'm using the body tag for example

Related

Jquery datatables. Array of rows of visible columns

I'm trying to extract an array of rows from my datatable. My problem is that I have some fields of the json that populates the table that I don't show in the table. When I use
$('#myTable').DataTable().rows().data().toArray()
I get those fields that I don't need.
¿How can I get that array of the shown fields or columns?
Thanks in advance.
You need to use a selector-modifier.
$('#myTable').DataTable().rows({search:'applied'}).data().toArray();
-------------------------------------
EDIT
A possible way to accomplish what you are asking for is to check first what columns are visible. Then, process each result row and get only the fields you want.
var columns = $('#myTable').DataTable().columns().visible();
var rows = $('#myTable').DataTable().rows().data().toArray();
var result = []; // this array will contain only the visible fields of each row
for (var i = 0; i < rows.length; ++i) {
var row = [];
for (var j = 0; j < columns.length; ++j)
if (columns[j]) // is visible
row.push(rows[i][j]);
result.push(row);
}

dynamically created table doesn't recognize unordred list tags

when i try to place an unorderd list fetched from the database column, into a dynamically created row of a table(using createElement) it shows the list tags along with the data. but doesn't appear formatted.
here is the code
var table1 = document.getElementById('pc');
for (var x = 1; x < len; x++) {
var vals = result[x];
var row = document.createElement('tr');
row.textContent = vals;
table.appendChild(row);
}
result is from ajax and it has the lists.
By "it shows the list tags along with the data" do you mean it is actually showing the <li> tag instead of actually making a list item?
It might be storing it in your database as < instead of <.

set limit for the number of columns per row in a html table

May I know what are the ways to limit the number of columns of a Html table (e.g. 3 columns per row)?
FYI, I'm using row.insertCell() to add cells to a particular row with matching the row id. I wish to limit the cell number to only 3 per row in the table.
"Limit"? There's no natural limit. You'll have to enforce it yourself on your own code.
Check if the row you're inserting into already has 3 cells, and don't add a new one if it does.
Use row.cells collection to check, how many cells a row contains.
var row = document.getElementById('row_id'),
cells = row.cells, max = 3;
if (cells.length < max) {
// Add cell(s) to #row_id
}
There is no such limit in the javascript or html standard. you have to enforce it yourself as a rule during the insertion.
A simple counter does the trick.
var items = ['c00', 'c01', 'c02', 'c10', 'c11', 'c12']; //sample data
var table = document.getElementById("myTable");
var row;
for(var i = 0; i < items.length; i++){
if(i % 3 == 0) { //after every third cell add a new row and change the row variable to point to it
row = table.insertRow(-1);
}
var cell = row.insertCell(-1); //simply insert the row
cell.innerHTML = items[i];
}
there are a number of ways of doing it. it will really depend on how you structure your code.
for(i=0;i<3;i++)
row.insertCell()

How to sort a table knowing row position?

I have a table:
<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
An array that tells where every row should come [{index: 2},{index: 1},{index: 0}] (first row is the last from the array, second row is the 1 in array and third row 0 from the array).
Here is my approach.
// create a new temporary tbody outside the DOM (similar to jQuery's detach)
var tbody_tmp = document.createElement('tbody');
// itterate through the array in the order of a new table
for(var i = 0, j = data.length; i < j; i++)
{
// make a copy of current row (otherwise, append child removes the row from the rows array and messes up the index-finder; there got be a better way for this)
var row = rows[data[i].index].cloneNode(true);
tbody_tmp.appendChild(row);
// reset the index to reflect the new table order (optional, outside the sample)
data[i].index = i;
}
// Note that tbody is a jquery object
tbody.parent()[0].replaceChild(tbody_tmp, tbody[0]);
Though, the cloning approach is slow. With 10,000+ records it takes ~1200ms. Furthermore, a jQuery-less approach is preferable.
Posting this in case someone else might find it simple enough for their needs (with less than 1,000 rows).
After hours of restless thinking, I've ended up with the following. If this sample isn't enough, I've written a whole blog post explaining the logic behind it, http://anuary.com/57/sorting-large-tables-with-javascript.
// Will use this to re-attach the tbody object.
var table = tbody.parent();
// Detach the tbody to prevent unnecessary overhead related
// to the browser environment.
var tbody = tbody.detach();
// Convert NodeList into an array.
rows = Array.prototype.slice.call(rows, 0);
var last_row = rows[data[data.length-1].index];
// Knowing the last element in the table, move all the elements behind it
// in the order they appear in the data map
for(var i = 0, j = data.length-1; i < j; i++)
{
tbody[0].insertBefore(rows[data[i].index], last_row);
// Restore the index.
data[i].index = i;
}
// Restore the index.
data[data.length-1].index = data.length-1;
table.append(tbody);

2D array with getElementsByTagName?

I am trying to access table cells in javascript using the getElementsByTagName method as shown below. Ultimately I want to compare each cell in the array to another value, and be able to change the background color of that cell according to the comparison.
var cells = document.getElementById("myTable").getElementsByTagName("tr");
for (i = 0; i < cells.length; i++)
{
cells[i] = cells[i].getElementsByTagName("td");
}
However, if I try to access cells[0][0], it returns undefined. I feel like I don't fully understand getElementsByTagName is doing... is there any hope for this method? Is there a more efficient one?
use jquery it will be simple :
var contentArray = new Array();
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});
You can access any cell directly using the table element's .rows property, and the tr element's .cells property:
var myCell = myTable.rows[y].cells[x];
No need to build your own array.
So don't use .getElementsByTagName(), which returns a one-dimensional array. (Well, actually a NodeList, but you can use it like an array as long as you remember that it is live.)
If you did want to loop through all cells to compare them to some other value here's how, left to right, top to bottom using .rows and .cells:
var rows = document.getElementById("myTable").rows;
for (var y=0; y < rows.length; y++) {
for (var x=0; x < rows[y].length; x++) {
var cellAtXY = rows[y].cells[x];
cellAtXY.someProperty = something; // your code here
}
}
You need to do something like this for each row.
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
then build your array from the contents of these variables.
Use this to get the table cells as 2D array
var tableRows = (document.getElementById("myTable")).getElementsByTagName("tr");
var cells = [];
for(var i = 0; i < tableRows.length; i++) {
cells.push(tableRows[i].getElementsByTagName("td"));
}
And now you can get any cell on your table using
cells[0][0]

Categories

Resources