Read td values by tr id from the same table - javascript

I am trying to read the values of table based on the tr id, but cannot wrap my head around how to do this.
// Id of the tr in question for example.row_17
var d =c["id"];
console.log(d);
// Here I can read all the td values, but I only want
// the ones inside the tr id = "row_17"
var cols =document.getElementById('report_table').getElementsByTagName('td'),
colslen = cols.length, i = -1; > while(++i < colslen)
{ console.log(cols[i].innerHTML);
}

Since you tagged it with jQuery, you can do it by doing something like this:
var id = c["id"];
// Select only the row with id specified in 'id' and loop through all 'td's' of that row.
$("#" + id).find("td").each(function()
{
// Log the html content of each 'td'.
console.log($(this).html());
});

Just in case you want a solution for JavaScript only (no jQuery):
var id = c["id"];
var tds = document.querySelectorAll('#' + id + ' td');
for(var i = 0; i < tds.length; i++) {
console.log(tds[i].innerHTML);
}
Demo

Related

how to add a div for dynamic table Td (not Th)

function table() {
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.className = 'table2';
var id = 0;
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 4; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
td.id = "td" + id ;
id++;
}
}
$(".middletablediv").append(tbl);
};
table();
i have dynamic table which contain td and th i add div for table td but it also effect the th .i don't want that div in th i want div only in div
$('tr:first-child').children('td').replaceWith(function(i, html) {
return '<th>' + html + '</th>';
});
this code is used for change first row td into th
and
$('#table td').wrapInner('<div class="tddivcolor divtime" />');
this for adding class to td
The only reason I could see is the order of your script execution.
If you are running the wrapping code first then the td->td conversion code then the divs will get added to the first row also.
So one solution is to fix the order and move the th conversion code first.
If that is not possible then you can exclude the first row from wrapping
$('#table tr:not(:first-child) td').wrapInner('<div class="tddivcolor divtime" />');
If you know the specific, try to use append if it works for you.
<table><tr><td>...
this not be the exact answer you need, but might lead to proper direction.
like where you want to put div, then try this, i used this to my selector class to create 'div'
$("#SelectorID").append("<div class= EmpList id=" + empID + ">" + selectedList[empID] + " <span class='close'>×</Span> </div>");

Add data-title from headline to every td with Javascript (for loop in two dimensional array)

I've got an html table where I want to add the cell content from the headline as data-title to every td for responsive html tables.
The problem is, when I want to set the attribute for the tbody cells, that I got the message:
"array[i] is undefined".
My Javascript Code looks like this:
function myFunction() {
var head = document.querySelector("table > thead");
var body = document.querySelector("table > tbody");
var columncount = body.rows[0].cells.length;
var headItems = head.rows[0].cells;
var headRows = head.rows;
var headCells = [];
var array = []
if (headItems.length == columncount) {
for (var i = 0; i < headRows.length; i++) {
var columns = [];
headCells = headRows[i].cells;
for (var m = 0; m < headCells.length; m++) {
columns[m] = headCells[m].innerHTML;
}
array[i] = columns;
}
}
var bodyRows = body.rows;
for (j = 0; j < bodyRows.length; j++) {
var bodyCells = bodyRows[j].cells;
for (k = 0; k < bodyCells.length; k++) {
bodyCells[k].setAttribute("data-title", array[i][m]); // NOTE array[i][m] here
}
}
}
If you use jQuery in your project this could help:
// Add data-title to every <td>
$( "table" ).each( function( index, tableID ) {
$( tableID ).find( "thead tr th" ).each( function( index ) {
index += 1;
$( tableID ).find( "tbody tr td:nth-child(" + index + ")" ).attr( "data-title", $(this).text() );
});
});
Works only for tables which have <thead> and <tbody> tags inside.
First of all, when you choose a variable, don't use a javascript keyword name, for example, instead of using array, use _array or arr or other variables.
I think you need to add a content to this array. Try to add something to your array, because if you do array[i], array is empty and don't have i index.
Try this:
_array.push(some_value);
Then, you can do this _array[0] for instance.

How to get th when child td is clicked?

I trying to get the <th> content of the clicked <td> item.
here is the fiddle: http://jsfiddle.net/zrccq447/
the thing is, the <th> can have colspan 2 or 3, this is the point where I am stuck. this is my code
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + (clicked_pos) + ')').text();
var xy = td.text();
alert(x);
});
i want x to be the <th> of clicked td. the problem is now that if you click on some td that shares the th with other tds, i am getting the wrong th.
appreciate any help
I've updated your JsFiddle with the answer found here: Finding a colSpan Header for one of the cells or td's is Spans
JsFiddle: http://jsfiddle.net/zrccq447/4/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var x = $('#headerx9 th:nth-child(' + thLocator[clicked_pos] + ')').text();
var xy = td.text();
alert(x);
});
var thLocator = [], colCount = 1;
$('#table9').find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
Following on from my comment you need to sum up the colspans (or default 1) for each TH until you get enough to match the column you desire:
http://jsfiddle.net/TrueBlueAussie/zrccq447/5/
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
var cols = 0;
var $table = td.closest('table');
var $ths = $table.find('tr th');
for (var i = 1; i < $ths.length; i++) {
var $th = $ths.eq(i);
cols += ~~$th.attr('colspan') || 1;
if (cols >= clicked_pos) {
var x = $th.text();
alert(x);
break;
}
}
});
I tried to keep it generic, so it finds the appropriate table and headers on the fly.
One approach is to get store a reference to each TH, in order, in an array and call the text from the array based on the location of the td.
var thholder = $('table th'),
th = [];
for(var i = 0; i < thholder.length; i++) {
var thi = $(thholder[i]);
for(var j = 0; j < (thi.attr('colspan') || 1); j++) {
th.push(thi);
}
}
$('#table9').on('click', 'td:not(:nth-child(1))', function () {
var td = $(this);
var clicked_pos = td.index();
alert(th[clicked_pos].text());
});
http://jsfiddle.net/zrccq447/3/
This code is not optimised, but shows the approach:
Loop through all the TH in the table.
If the TH does not have the attribute 'colspan', then set the attribute to a value of 1.
Create a loop for each value of colspan and save a reference to the current TH in the array.
When you click on a TD, get it's clicked position and retrieve the text of the TH at that position in the array and alert it :)

Mobile Tables - Jquery, so close, stuck on the last part

I'm trying to make a script to make my applications tables more mobile friendly.
The tables are all very similar, but very in number of row and columns, since they will be dynamically created, I'll have little control over this, so i've come up with the script below, it almost works but one function is not be passed on to each table, it stops after the first.
I suggest looking at the js fiddle: http://jsfiddle.net/e4vC3/1/
Here is the piece of the script that is not working correctly:
// Create content for new headers in mobile table by copying from original table
var HeaderArray = [];
$("table thead tr th").each(function(){
var innerArray = [];
$(this).each(function () {
innerArray.push($(this).text());
});
HeaderArray.push(innerArray); // Put content for new headers in array
});
$("table.mobile_table tbody tr").each(function(index, elem){ // Place content of array where array position and row index are the same
$(this).find("td").first().text(HeaderArray[index]);
});
Again, if you check the fiddle, you will see that the first arry stops copying objects after the first table, i cant get it to run all the way thought.
If anyone could help me with them, i would really, realy appreciate it..... http://jsfiddle.net/e4vC3/1/
The problem is that there are multiple data rows while only 1 header row. So, you will have to use mod operator like this(index has been replaced with index % TableSize):
$("table.mobile_table tbody tr").each(function(index, elem){ // Place content of array where array position and row index are the same
$(this).find("td").first().text(HeaderArray[index % TableSize]);
});
Updated your code # http://jsfiddle.net/souviiik/e4vC3/4/, see if this is helpful. For the first mobile_table I was not able to put the TH values, I hope you can modify my code :)
var TableSize = $("#ContactsPhoneTable .tableHedaer").size(); // Get # of columns
var i = 1;
var TableRowCount = $(".no_edit").size(); // Get # of body rows
$(".tableHedaer").each(function () {
$(this).attr("id", i++); // Give headers incrementing ID
});
for (var CreateTables = 1; CreateTables < TableRowCount; CreateTables++) { // Create new table class="mobile_table" for each row
$("table").after("<table class='mobile_table'></table>");
}
for(var i = 0 ; i < TableSize ; i++)
{
var tableRow = $("<tr/>").appendTo(".mobile_table");
for(var j = 0 ; j < TableRowCount ; j++)
{
var cellValue = $("#ContactsPhoneTable").find("tr").eq(i).find("td").eq(j).text();
$("<td/>", {
text: cellValue
}).appendTo(tableRow);
}
}
Updated code is at http://jsfiddle.net/souviiik/b6QZT/2/, see if this is acceptable. The code is as below.
var columnCount = $("table thead tr th").not("table.mobile_table thead tr th").size(); // Get # of columns
var rowCount = $("table tbody tr").size(); // Get # of body rows
for (var CreateTables = 0; CreateTables < rowCount; CreateTables++) { // Create new table class="mobile_table" for each row
$("<table/>", {
"class": "mobile_table"
}).appendTo(".newTableContainer");
}
var tableHedaers = [];
for(var th = 0 ; th < columnCount ; th++)
{
tableHedaers.push($(".sortable th").eq(th).text());
}
$(".mobile_table").each(function(idx){
var thisTable = $(this);
for(var i = 0 ; i < columnCount ; i++)
{
var thisTableRow = $("<tr/>").appendTo(thisTable);
for(var j = 0 ; j < 2 ; j++)
{
if(j == 0)
{
$("<td/>", {
"text": tableHedaers[i],
"style": "font-weight: 700"
}).appendTo(thisTableRow);
}
else
{
var cellValue = $("#ContactsPhoneTable").find("tr").eq(idx+1).find("td").eq(i).text();
$("<td/>", {
"text": cellValue
}).appendTo(thisTableRow);
}
}
}
});

Create HTML table from javascript array

I want to get all classes of the HTML element on my page, split it and store it in array. After that I want to write it into my table in the div with the id "table" which I already have.
So far I have this code:
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
// code
}
<div id="test><!-- table goes here --></div>
Can you help me with the rest?
btw, the HTML element has the classes from a modernizr.js.
PS: The code is combination of pure JS and jQuery. Because I dont know how to get all classes of the HTML element in pure JS. Any Idea?
If you're trying to remove jQuery altogether use this:
// Get array of classes without jQuery
var array = document.getElementsByTagName('html')[0].className.split(/\s+/);
var arrayLength = array.length;
var theTable = document.createElement('table');
// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(array[i]));
tr.appendChild(td);
theTable.appendChild(tr);
}
document.getElementById('table').appendChild(theTable);
if you have a table already in the html
<div id="test><table >
</table>
</div>
you can simply append new rows to it,
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
$("#test table") .append('<tr><td>'+array[i]+'</td></tr>')
}
It is not clear if you want the class names per row or per column. These examples are one class name per row. Try this:
var elm = $('#test'),
table = $('<table>').appendTo(elm);
$(document.documentElement.className.split(' ').each(function() {
table.append('<tr><td>'+this+'</td></tr>');
});
I used native code to get the classNames of the HTML element: document.documentElement.className, but you might as well use $('html').attr('class').
A native JS example using innerHTML:
var d = window.document,
elm = d.getElementById('test'),
html = '<table>',
classes = d.documentElement.classNames.split(' '),
i = 0;
for(; classes[i]; i++) {
html += '<tr><td>' + classes[i] + '</td></tr>';
}
elm.innerHTML = html + '</table>;

Categories