How to use javascript to print table dynamically? - javascript

I want print a table dynamically, but my program displayed in a messy way.
I hope each row conludes two elements. I want to display the table like this. In 1s it gets a name and display it. And in next 1s it gets another name and display it. By repeating in this way, display all data.Here is my main code.
var count = 0;
function AddTd(id, showname)
{
console.log(id);
if(id == 0) // if this is in the first column
{
var str = '<tr><td width="10px">'+showname+'</td>';
$("#datashow").append(str);
count = 1; // next element should in second column
return;
}
if(id == 1) // if this is in the second column
{
var str = '<td width="10px">'+showname+'</td></tr>';
$("#datashow").append(str);
count = 0; // next element should in first column
return;
}
}
setInterval('change()',50); // In function change, print the table dynamically

This should create table with as many elements as there will be in array and do 2 columns per row.
http://jsfiddle.net/XfKME/3/
var names = ["name1", "name2", "name3", "name4"];
var tbody = "<table>";
$.each(names, function (i, item) {
if (i % 2 == 0)
tbody += "<tr>";
tbody += "<td>";
tbody += item;
tbody += "</td>"
if (i % 2 == 1)
tbody += "</tr><br />";
});
tbody += "</table>";

Related

Copy row from any table

I have an HTML page with 3 tables on it. I want to be able to copy specific cells in a table row to the clipboard. The row could come from any of the 3 tables.
Using the code below, I highlight and copy the row for a table with an ID of "final". How do I make this work for any of the 3 tables? I tried by getElementsByTagName and labeling them the same name but did not work - understandably so. Is there a way to designate the selected table? I am trying to avoid copying the whole row and might eventually add the formatted msg to a new page rather than copy to the clipboard.
function copy_highlight_row() {
var table = document.getElementById('final');
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function () {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.style.backgroundColor = "yellow";
rowSelected.className += " selected";
var cellId = this.cellIndex + 1
msg = 'Title: ' + rowSelected.cells[0].innerHTML;
msg += '\r\nDescription: ' + rowSelected.cells[1].innerHTML;
msg += '\n\nLink: ' + rowSelected.cells[2].innerHTML;
msg += '\nPublication Date: ' + rowSelected.cells[3].innerHTML;
//msg += '\nThe cell value is: ' + this.innerHTML copies cell selected
navigator.clipboard.writeText(msg);
}
}
};
Based on a couple of the suggestions I came up with the following:
function highlight_row() {
var cells = document.querySelectorAll('td')
for (var i = 0; i < cells.length; i++) {
// Take each cell
var cell = cells[i];
// do something on onclick event for cell
cell.onclick = function () {
// Get the row id where the cell exists
var rowId = this.parentNode.rowIndex;
var t_ID = this.closest('table').id
var table=document.getElementById(t_ID);
var rowsNotSelected = table.getElementsByTagName('tr');
for (var row = 0; row < rowsNotSelected.length; row++) {
rowsNotSelected[row].style.backgroundColor = "";
rowsNotSelected[row].classList.remove('selected');
}
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.style.backgroundColor = "yellow";
rowSelected.className += " selected";
var cellId = this.cellIndex + 1
msg = 'Title: ' + rowSelected.cells[0].innerHTML;
msg += '\r\nDescription: ' + rowSelected.cells[1].innerHTML;
msg += '\n\nLink: ' + rowSelected.cells[2].innerHTML;
msg += '\nPublication Date: ' + rowSelected.cells[3].innerHTML;
navigator.clipboard.writeText(msg);
}
}
}
At the end of the html I call the function. The HTML contains 3 tables and this enabled me to click on any table, highlight the row, and copy the correct range of cells.

Read CSV rows into array to display individual rows in different areas of page

I have been able to successfully read in a CSV file from a URL, parse through it, and write it out to a table. Simple to most but a Herculean effort for me. There is a header row, and each row contains 4 values (the first will be disregarded).
What I need to do is to be able to write each row to a different place on my page at will. I assume to do this I'd need to load each row into a slot in an array, where I can then call them specifically. For example if I want the 3rd entry, and also be able to access each value to build my text string, it would have to look something like:
document.getElementById("snow").innerHTML = 'Trail Status: ' + trail[2].status + 'Report Date: ' + trail[2].reportDate;
I know that the above code probably is flawed, but it was more illustrative than anything.
What I don't know how to do is setup an array to hold each row (so they can be accessed individually), define each value so it can be a accessed (trail, reportDate,etc), and read the CSV properly into that array.
I'm currently using jQuery and the code below to read, parse, and create the table.
$.ajax({
url: 'https://data.import.io/extractor/...',
dataType: 'text',
}).done(successFunction);
function successFunction(data) {
var allRows = data.split(/\r?\n|\r/);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th>';
table += rowCells[rowCell];
table += '</th>';
} else {
table += '<td>';
table += rowCells[rowCell];
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
table += '</tbody>';
table += '</table>';
$('body').append(table);
}
Any direction to reaching my end state would be greatly appreciated. Ultimately I'm building a dashboard that will show the Trail Conditions (from the CSV) and 10-day weather forecast (from Wunderground) to help plan Snowmobile Trips for local Michigan snowmobilers.
Thanks!
Marc
Create a multidimensional array - with 2 dimensions. The first index will access each row. The second index will access each cell within a row.
This reference may help: https://trans4mind.com/personal_development/JavaScript/Array2D.htm
This is an example using your current for loops.
function successFunction(data) {
var parsedData = [];
var allRows = data.split(/\r?\n|\r/);
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
parsedData[singleRow][rowCell] = rowCells[rowCell];
}
}
}
Thanks for the input, i found that PapaParse was the way to go! The data was easy to get at and I had no problems!

From a dynamic table, save separate tables from the master table

Say I have a dynamic table, something like this (just an example):
var table = '<table>';
for (var i=0; i<6; i++) {
table += '<tr>';
table += '<th>';
table += 'HEADER ' + i + '</th></tr>'
table += '<tr><td>one</td>';
table += '<td>two</td>';
table += '<td>three</td>';
table += '<td>four</td>';
table += '<td>five</td>';
table += '<td>six</td>';
table += '<td>seven</td>';
table += '<td>eight</td>';
table += '</tr>';
}
table += '</table>';
What I'd like to do is to take each header and its table data under the header and save each as a separate table. For example, the first table would be:
HEADER 0
1 2 3 4 5 6 7 8
The second table would be:
HEADER 1
1 2 3 4 5 6 7 8
etc...
NOTE: There's no guarantee that there's only one row under each header. Some may have multiple rows.
To get the first table I could do:
var indexval = $(table).find('tr:contains("1")').index();
var firstTable = $(table).find('tr:lt('+indexval+')');
$('#testarea').html(firstTable);
I'm aware I'm calling these "tables" and that may not be correct. But how to start at the "next" header and go the the one after that and save 'that' table? In the end I'd have a number of little tables I could print to the screen by calling their variable names.
Demo:
var table = '<table>';
for (var i = 0; i < 6; i++) {
table += '<tr>';
table += '<th>';
table += '<td>HEADER ' + i + '</td></th></tr>'
table += '<tr><td>one</td>';
table += '<td>two</td>';
table += '<td>three</td>';
table += '<td>four</td>';
table += '<td>five</td>';
table += '<td>six</td>';
table += '<td>seven</td>';
table += '<td>eight</td>';
table += '</tr>';
}
table += '</table>';
//$('#testarea').html(table);
var indexval = $(table).find('tr:contains("1")').index();
var firstTable = $(table).find('tr:lt(' + indexval + ')');
$('#testarea').html(firstTable);
td, th {
min-width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='testarea'></div>
EDIT: I ended up solving my own problem by just using a couple of arrays to store each section of the table (each header and its immediate relevant rows under it). The first for loop gets the index value of the header, and the second for loop selects out the table rows (header and associated cells under it). The "firstRow" variable selects just the first header and its rows, the 'lastRow' variable does the same with the last header and row(s). Apologies for not initially putting the question in clear terms. The question was just asking how to segment out a large table into pieces with each header and its relevant rows underneath and save them as separate variables. My thinking was this would clean up my pagination method I've currently got on my site. When a 'page up' or 'page down' is clicked, it just loads the appropriate variable in the div on the page.
var firstRow = "";
var test = [];
var indexVal = [];
for (var i=2; i<7; i++) {
indexVal[i] = $(table).find('tr:contains('+('MC' + ' ' + i)+')').index();
}
firstRow = $(table).find('tr:lt('+indexVal[2]+')');
lastRow = $(table).find('tr:gt('+((indexVal[6]) - 1)+')');
for (var j=1; j<7; j++) {
test[j] = $(table).find('tr:lt('+indexVal[j + 1]+'):gt('+((indexVal[j]) - 1)+')');
}
The only issue I had was not being able to integrate the first and last rows into the for loops. I had to make them separate hand coded variables. But it works.
JSFIDDLE

dynamically creating a table and adding cells to the table through a function with Javascript

I am wondering how to create a function with a for loop which creates new cells / rows for the other for loop to call upon. The function should return newRow which should be a specified amount of cells. The idea is the html code displays 3 images per row, but if there is just 2 images then it only needs 2 cells. That is the first if / else statement.
Here is the code so far..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//loop once per row
var htmlStr = '';
for (var i = 0; i < num; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '</tr>;
if (num - i >= NUMPERROW) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
*Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}
Here is a simple function if you don't want to pass the values you can leave content out.
function newRow(numberOfCells, content)
{
var result = '<tr>';
for(var i = 0; i < numberOfCells; i++)
result += '<td>' + content[i] + '</td>';
result += '</tr>';
return result;
}

Find the value of html table cell by passing column name for a particular row

I am dynamically creating a table using JSON so i dont know in advance how many column and/or rows will be generated.
I add a clicked event for the row that get selected.
Now my every table will have a column name ID
I want to find the value of ID for the selected row.
How can i achieve this?
I have googled a find a lot of sample which select the cell be index but not by column name.
My table is something like:
My table is generated like:
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + val(array[i][index]) + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
Any help is appreciated
I hope i understood you correctly but this should do it.
It alerts the content of the td with the name ID of the clicked tr.
$('tr').live('click',function(){
alert( $(this).find('td[name="ID"]').html() );
});
To find the td via the th with text ID you could do this:
var index = $('yourtable th:contains("ID")').index();
alert( $('.selectedRow td:eq('+index+')').html() );
What I would do though is to save the ID in the TR's data object so you won't have to pull it out the td but can access it directly, like this:
[...]
<tr data-id="26"><td>.....</td></tr>
[...]
then you can access it like that:
$('.selectedRow').data('id');

Categories