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>");
Related
I am trying to populate table data dynamically in JavaScript. I managed to populate it but there is some problem with the styling, here is what I have achieved so far:
And my code to achieve the above:
function populateOverallOverview(result){
var tableData = new Array();
var table = document.getElementById("firstTabOverall");
for(var i = 0; i < result.length; i++){
tableData[i] = new Array('Category: ' + result[i].category + '\n Best selling month: ' + result[i].topMonthStr + '\n Amount: ' + result[i].topAmount.toFixed(2));
}
for(var i = 0; i < tableData.length; i++){
var newRow = table.insertRow(table.length);
for(var j = 0; j < tableData[i].length; j++){
var cell = newRow.insertCell(j);
cell.innerHTML = tableData[i][j];
}
}
}
My HTML code:
<div class="col-md-6">
<table id="firstTabOverall" class="table table-striped" style="font-size:13px">
</table>
</div>
What I wanted to achieve is for each row, there will be 3 different sub-rows for category, best selling month and amount. I am trying to split them into the next line using '\n' but it does not work.
Also, is there any way to bold the category, best selling month and amount wording in this case?
You do quite some unnecessary shifting-around of data. From results into a temp array, from the temp array into the table... why not from results straight into the table? Also, of course \n does not work. Line breaks mean nothing in HTML. You must add each cell individually.
The following looks a lot more straight-forward – and the Array#forEach() method rids you of the need for a separate loop counter, too:
function populateOverallOverview(result){
var table = document.getElementById("firstTabOverall");
// helper function
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
// insert data
result.forEach(function (item) {
var row = table.insertRow();
addCell(row, 'Category: ' + item.category);
addCell(row, 'Best selling month: ' + item.topMonthStr);
addCell(row, 'Amount: ' + item.topAmount.toFixed(2));
});
}
Instead of repeating the category names in front of the values, write them into the header row. That's how a table is supposed to work anyway, right?
So, maybe this is better:
function populateOverallOverview(result){
var table = document.getElementById("firstTabOverall");
// helper function
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
// create header
var thead = table.createTHead();
var headerRow = th.insertRow();
addCell(headerRow, 'Category');
addCell(headerRow, 'Best selling month');
addCell(headerRow, 'Amount');
// insert data
result.forEach(function (item) {
var row = table.insertRow();
addCell(row, item.category);
addCell(row, item.topMonthStr);
addCell(row, item.topAmount.toFixed(2));
});
}
Use CSS to style your table and table header. It might be easier to just write the header row into the static HTML source up-front.
If you positively must add bold text inline labels, you could use these document.createElement("b"), to get a <b> element, set its .textContent and then use .appendChild() of the respective container, in this case of the table cell.
You can add plain text the same way - just use document.createTextNode('...your text...') instead and append that.
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
Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!
Suppose I have these three spaces that are blank to start with. I want to change using innerHTML in JavaScript.
<p id="topname"></p>
<div id="table"></div>
<p id="botname"></p>
document.getElementById("topname").innerHTML = "Boy";
document.getElementById("botname").innerHTML = "Girl";
I managed to change topname and botname with the innerHTML. How do I change div id="table" to display an x by y (2x2, 4x4, 8x8,etc.) table?
Instead of replacing the <div> with a <table>, it is recommended to create a <table> as a child node of the <div> As long as you have not added additional styling to the <div> (like padding or margins), this will have no effect on the display.
A couple of loops to build <tr> and <td> will do the job. Here's a function that takes x and y:
function makeTable(rows, cols) {
// Create a table node
var tbl = document.createElement('table');
// Make a <tr> for each row
for (var i=0; i<rows; i++) {
var tr = document.createElement('tr');
// And make a <td> for eah col
for (var j=0; j<cols; j++) {
var td = document.createElement('td');
// Append them to the current tr
tr.appendChild(td);
}
// Append the row
tbl.appendChild(tr);
}
return tbl;
}
// Create a new 2x4 table with the function
var newTable = makeTable(2, 4);
// And append it as a child to the <div id='table'>
document.getElementById('table').appendChild(newTable);
Here it is in action
You should be able to do it the same way, however, that div id might be giving you issues. TABLE is an html entity unto itself. I would rename that.
document.getElementById("table").innerHTML = "<table><caption>Caption</caption><thead>Table Header</thead><tfoot>Table Footer</tfoot><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>";
And what Shadow Wizard said above. It is best to use the right tool for the job. My answer is solely if you insist on doing it within a div.
First of all, change your div to a table manually:
<table id="table"></table>
With following code you can fill your table with rows and columns:
document.getElementById("table").appendChild(makeTable(2, 4));
function makeTable(rows, cols) {
var table = document.createDocumentFragment(), tr = document.createElement("tr"), td = document.createElement("td"), i, j;
for(j = 0; j < cols; j++) tr.appenChild(td.cloneNode(true));
for(i = 0; i < rows; i++) table.appendChild(tr.cloneNode(true));
return table;
}
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>;