how to use javascript or jquery create table fast - javascript

I want to create a table by click a button,and i need to save the table to the database .this is the code to create table but i think this is so long,how can i create it fast?
var div = document.createElement("div");
var table1 = document.createElement("table");
var table2 =document.createElement("table");
var thead = document.createElement("thead");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
var th3 = document.createElement("th");
th1.innerHTML="Count";
th2.innerHTML="Date";
th3.innerHTML="Price";
document.body.appendChild(div);
div.appendChild(table1);
div.appendChild(table2);
table2.appendChild(thead);
thead.appendChild(th1);
thead.appendChild(th2);
thead.appendChild(th3);

If the code is too long then I recommend creating an html table structure inside a div that is not displayed. Then when the user clicks the button then you could
Display the table that is hidden.
Clone the table and append it to something (if you expect to create the table multiple times)
Your code would then look like so (cloning wise):
jQuery:
$('#myButton').on('click', function(){
$(document.body).append($('original').clone());
});
Javascript:
document.getElementById('myButton').onclick = function(){
document.body.appendChild(document.getElementById('original').cloneNode());
}
And here is the html table you can have hidden.
<div style="display: none;">
<table id="original">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</div>
This reduces greatly your javascript code.

If you want to make some enhancement than you can use precompiled template like muchtache.js :
<table>
<tr>
<th> Count </th>
<th> Date </th>
<th> Price </th>
</tr>
{{#jsonObject}}
<tr>
<td>{{Count1}}</td>
<td>{{Date1}}</td>
<td>{{Price1}}</td>
</tr>
{{/jsonObject}}
</table>
in javascript, you can write your javascript jsonobject as :
jsonobject : [{
count1 : 1,
date1 : 12/12/2012,
price1 : 100
},
{
count1 : 2,
date1 : 12/12/2013,
price1 : 200
}
]
for full muchtache example visit Json Object into Mustache.js Table

The following function might help:
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}
Here is how to use it:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<table></table>'
+ '<table>'
+ '<thead>'
+ '<th>Count</th>'
+ '<th>Date</th>'
+ '<th>Price</th>'
+ '</thead>'
+ '</table>'
+ '</div>'
));
Live demo:
document.body.appendChild(html2dom(''
+ '<div>'
+ '<p>Paragraph.</p>'
+ '<ul>'
+ '<li>Item 1.</li>'
+ '<li>Item 2.</li>'
+ '<li>Item 3.</li>'
+ '</ul>'
+ '</div>'
));
function html2dom (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.removeChild(div.firstChild);
}

Related

javascript to add rows to a table dynamically

I'm trying to figure out how to use javascript to add rows to a table dynamically. I tested without the table and can get the data but am stumped on populating the table.
I have a function call on a button that is supposed to populate the table. below is my code so far:
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>
function getData()
{
var soData = JSON.parse(staffOrders);
var i = 0;
var c = getRowCount();
//build table
var table = document.getElementById("tblData");
while (i <= c) {
//alert(soData[i].staffName + " had " + soData[i].orders + " orders.");
//"<td>" + soData[i].staffName + "</td>"
//"<td>" + soData[i].orders + "</td>"
i++;
}
}
You need to use the DOM API for the HTML table element. It's documented at
http://www.w3schools.com/jsref/dom_obj_table.asp
Here's an example taken from http://www.w3schools.com/jsref/met_table_insertrow.asp :
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
function getData() {
var responseData = [{
"staffName": "Wilkerson Bowman",
"orders": 26
}, {
"staffName": "Finley Nunez",
"orders": 26
}, {
"staffName": "Katie Estrada",
"orders": 7
}];
var thead = document.querySelector('#tblData thead');
responseData.forEach(function(data) {
var row = document.createElement('tr');
row.innerHTML = '<td>' + data.staffName + '</td><td>' + data.orders + '</td>';
thead.appendChild(row);
});
}
getData();
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody></tbody>
</table>
try this code
window.onload = function(){
function getData() {
var soData = [{orders : 'order1', staffName : 'staffName1'}, {orders : 'order2', staffName : 'staffName2'}]
var i = 0;
var c = 2;
//build table
var table_body = document.getElementById("tblData").getElementsByTagName('tbody')[0];
while (i <= c) {
var tr = document.createElement('tr');
tr.className = "pure-table-odd"; // add class in tr
var td1 = document.createElement('td');
td1.innerHTML = soData[i].orders;
var td2 = document.createElement('td');
td2.innerHTML = soData[i].staffName;
tr.appendChild(td1);
tr.appendChild(td2);
table_body.appendChild(tr);
i++;
}
};
getData();
}
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>

Writing the result of a Javascript for-loop into a HTML 5 table

I am playing about with Javascript, and I've made a fictional hotel website that shows you hotel details when you click on a button.
http://jsfiddle.net/addiosamigo/4ev43b5m/8/
var hotel = {Name: "Park Hotel", Price: "£120.00", Rooms: 50}
var hotel2 = {name: "West End", price: "£240.00", rooms: 150}
el_p = document.getElementById("para1");
el_picture = document.getElementById("picture");
el_picture2 = document.getElementById("picture2");
function showPrice() {
el_picture2.style.display = "none";
el_picture.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel) {
el_p.innerHTML += (details += ": " + hotel[details] + "<br />");
}
}
function showPrice2() {
el_picture.style.display = "none";
el_picture2.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel2) {
el_p.innerHTML += ( details += ": " + hotel2[details] + "<br />");
}
}
first of all, is there an easier way to code this? I'm just learning so I just did what I could.
second of all how do I write the results of my for loop into a table?
thanks
Here is a javascript version using an HTML template and pure javascript instead of jQuery.
http://jsfiddle.net/dr6n88bu/15/
<script type="text/template" id="hotelTemplate">
<img src="{img}" />
<table>
<tr>
<td>Name: </td>
<td>{name}</td>
</tr>
<tr>
<td>Price: </td>
<td>{price}</td>
</tr>
<tr>
<td>Rooms: </td>
<td>{rooms}</td>
</tr>
</table>
</script>
I suggest you to use jQuery library (based on JS).
1) Create array of hotels:
var hotels = [
{name: "Park Hotel", price: "£120.00", rooms: 50},
{name: "West End", price: "£240.00", rooms: 150}
];
2) Create empty table:
<table id="hotelsTalbe">
<thead>
<tr>
<th>Hotel name</th>
<th>Price per room</th>
<th>No. of rooms</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
3) Than just loop your hotels:
// Load jQuery first!
$.each(hotels, function(key, row){
// this - current element in loop. $(this) - current jQuery element.
$('#hotelsTable tbody').append(
'<tr><td>'
+ row['name'] + '</td><td>'
+ row['price'] + '</td><td>'
+ row['rooms'] + '</td></tr>'
);
});
In JS (not tested):
for (var i = 0; i < hotels.lenth; i++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
var text = document.createTextNode(hotels[i]['name']);
td.appendChild(textnode);
tr.appendChild(td);
document.querySelector("#hotelsTable tbody").appendChild(tr);
td = document.createElement("td");
text = document.createTextNode(hotels[i]['price']);
td.appendChild(textnode);
tr.appendChild(td);
td = document.createElement("td");
text = document.createTextNode(hotels[i]['rooms']);
td.appendChild(textnode);
tr.appendChild(td);
document.querySelector("#hotelsTable tbody").appendChild(tr);
}

How to read HTML <table> and sort the table content?

I have a html table with three columns [Title, Category, Sub-Category] and multiple rows . And I want to read the entire table content and make it categorized as below output.
My <html> table content is like this.
Title Category Sub
T1 C1 S1
T2 C2 S2
T3 C2 S3
T3 C1 S1
T2 C1 S3
T1 C2 S3
Here is the output format what I really need. I just want to print the above html table content in the below out put format.
T1 :
C1 : S1
C2 : S3
T2 :
C2 : S2
C1 : S3
T3 :
C2 : S3
C1 : S3
[Title]
[Category] :[Sub-Category]
Please help me.
Assuming the table has this code:
<table>
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Sub</th>
</tr>
</thead>
<tbody>
<tr>
<th>T1</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C2</td>
<td>S2</td>
</tr>
<tr>
<th>T3</th>
<td>C2</td>
<td>S3</td>
</tr>
<tr>
<th>T3</th>
<td>C1</td>
<td>S1</td>
</tr>
<tr>
<th>T2</th>
<td>C1</td>
<td>S3</td>
</tr>
<tr>
<th>T1</th>
<td>C2</td>
<td>S3</td>
</tr>
</tbody>
</table>
We can use jQuery to get output like this:
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = "";
$("tbody tr").each(function(){
s += $(this).find("th").html() + ":\n";
s += $(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html() + "\n\n";
});
$("textarea").val(s);
});
Fiddle: http://jsfiddle.net/praveenscience/9ueervw4/
The below code, you get a JavaScript object which is associative!
$(document).ready(function(){
$("table").hide();
$("body").append("<textarea></textarea>");
var s = {};
$("tbody tr").each(function(){
if (!s[$(this).find("th").html()])
s[$(this).find("th").html()] = [];
s[$(this).find("th").html()].push($(this).find("td:nth-child(2)").html() + ": " + $(this).find("td:nth-child(3)").html());
});
});
Try using associative arrays in javascript/jQuery: DEMO
var tableRowArray = $('table tr');
var titleArray = [];
var mainArray = {};
// build an associative array of the values int he table
tableRowArray.each(function(){
if($(this).children('th').length == 0) {
var tempTitle = $(this).children('td').eq(0).text();
if(mainArray[tempTitle]){
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
else {
titleArray.push(tempTitle);
mainArray[tempTitle] = {};
mainArray[tempTitle][$(this).children('td').eq(1).text()] = $(this).children('td').eq(2).text();
}
}
});
// print the formatted associative array to the page
$('body').append("<p></p>");
var formattedString = "";
$.each(titleArray, function(index, value){
formattedString += "<b>" + value + " : </b><br/>";
for(var key in mainArray[value]) {
formattedString += " " + key + " : " + mainArray[value][key] + "<br/>";
}
});
$('p').html(formattedString);
Basically, we create an associative array from your table and then the next piece iterates through the array to print it in the format you specified (you may need to edit the set up of the array if you table structure varies from what I used the in JSfiddle).
The below example will give you the output you want.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script language="javascript">
$(document).ready(function () {
var outputtemp = "<table>";
$("#tbl1 tr").not("tr th").each(function () {
outputtemp += "<tr>"
var i = 0;
$(this).find("td").each(function () {
if (i == 0)
outputtemp += "<td>" + $(this).text() + ":</td></tr><tr>";
else if (i == 1)
outputtemp += "<td></td><td>" + $(this).text() + ":</td>";
else
outputtemp += "<td>" + $(this).text() + "</td>";
i++;
});
outputtemp += "</tr>"
});
outputtemp += "</table>"
$(".output").html(outputtemp);
});
</script>
</head>
<body>
<table id="tbl1">
<tr>
<th>
Title
</th>
<th>
Category
</th>
<th>
Sub
</th>
</tr>
<tr>
<td>
T1
</td>
<td>
C1
</td>
<td>
S1
</td>
</tr>
<tr>
<td>
T2
</td>
<td>
C2
</td>
<td>
S2
</td>
</tr>
<tr>
<td>
T3
</td>
<td>
C3
</td>
<td>
S3
</td>
</tr>
</table>
<div class="output">
</div>
</body>
</html>
Get the data using getElementbyId and then you may apply any operation on that data when you have whole data in js variables.

Proper rows not getting colored

My rows are not getting colored properly"
Please have a look at my HTML output:
<table id="mytable" cellspacing="0" cellpadding="5">
<tbody>
<tr class="tableheader">
<th>Name</th>
<th>Code</th>
<th>Value</th>
<th>Bid</th>
<th>Offer</th>
</tr>
<tr class="rowoddcolor">
<td>Apple</td>
<td>APPL</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
<tr class="tablecontent">
<td>Microsoft</td>
<td>MSFT</td>
<td>78</td>
<td>70</td>
<td>75</td>
</tr>
<tr class="rowevencolor">
<td>Google</td>
<td>GOGL</td>
<td>101</td>
<td>98</td>
<td>102</td>
</tr>
<tr class="tablecontent">
<td>Nokia</td>
<td>NOK</td>
<td>10</td>
<td>8</td>
<td>9</td>
</tr>
<tr class="rowoddcolor">
<td>Samsung</td>
<td>SAMS</td>
<td>89</td>
<td>86</td>
<td>90</td>
</tr>
<tr class="tablecontent">
<td>IntelCorporation</td>
<td>INTC</td>
<td>111</td>
<td>112</td>
<td>110</td>
</tr>
</tbody>
</table>
Now only the 1st and 5th row getting colored? why not 3rd row?
updated code:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementsByClassName('tablecontent');
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
});
});
I am creating html through jquery consuming json. Table is getting created properly. Now through javascript, i am styling my alternate rows to different color and header should be in different color. This is my first question. Please see below my script:
function tablerows(id){
if(document.getElementsByTagName){
var tableid = document.getElementById(id);
var rows = tableid.getElementById("tablecontent");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "rowevencolor";
}else{
rows[i].className = "rowoddcolor";
}
}
}
}
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr id="tablecontent"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
});
$(function(){
tablerows('mytable');
});
});
But my rows are not getting styled. Please tell me where is the problem.
Below is css code as well:
.rowoddcolor{
background-color:#FFFFFF;
}
.rowevencolor{
background-color:#D3D3D3;
}
I believe the function "tablerows" is getting executed before the build of table. So put that code after the append method.
Example :
$(document).ready(function() {
$.getJSON('table.json',function(data){
// existing stuff
$('#mytable').append(html);
tablerows('mytable');
});
});
Also the easiest way add the color class on alternating would be :
$('#mytable tr:even').addClass("rowevencolor");
$('#mytable tr:odd').addClass("rowoddcolor");
A few things:
First, Element ID's should be unique. Do not give every tr the same id tablecontent.
After that's fixed, you can ditch the entire helper function tablerows() as it is redundant and that logic can be moved to where you are building the table, i.e.:
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent row' + (i % 2 ? 'even' : 'odd') + 'color"><td class="name">'+ data[i].name+ '</td><td class="code">'+ data[i].code+ '</td><td class="value">'
+ data[i].value+ '</td><td class="bid">'
+ data[i].bid+'</td><td class="offer">'+data[i].offer+'</td></tr>';
}
Or simply use psuedo-selectors in your CSS as recommended by Kundan
The reason why your code is not highlighting table row #3 is because the result of getElementsByClassName is a NodeList, not an Array.
You will thus need to convert the NodeList to an Array before using the indexing operator for random access.
e.g.
var rowsList = tableid.getElementsByClassName('tablecontent');
var rows = Array.prototype.slice.call(rowsList);
for (i = 0; i < rows.length; i++)
// ...
Here is a working fiddle
However, as per Kundan's answer, it seems strange why you wouldn't use a jQuery solution, as it is much less work. jQuery fiddle here

Getting the table row values with jQuery

I am trying to get the values from an HTML table row. When I click on the table row delete button, I want to put those values on variables to send to the server. I have found something from here that looks like what I need, but when I put it together for my scenario, it does not work.
Here is the table HTML:
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
and here is the jQuery:
var tr = $('#thisTable').find('tr');
tr.bind('click', function(event) {
//var values = '';
// tr.removeClass('row-highlight');
var tds = $(this).addClass('row-highlight').find('td');
$.each(tds, function(index, item) {
values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
alert(values);
});
What am I doing wrong? I keep looking at examples but I cant seem to make this work.
Try this:
jQuery('.delbtn').on('click', function() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function(i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
});
DEMO
Give something like this a try:
$(document).ready(function(){
$("#thisTable tr").click(function(){
$(this).find("td").each(function(){
alert($(this).html());
});
});
});​
Here is a fiddle of the code in action: https://jsfiddle.net/YhZsW/
All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML I believe. I use the jQuery html function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>​
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});

Categories