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>
Related
I have a simple HTML table that can contain 2-5 rows and 6 columns each. How can I get the value of 1 and 2 columns for each row? I would also like to display it in a output like this: Column1 Column2, Column1 Column2, Column1 Column2 would be the output if it has 3 rows.
EDIT: Created a jsfiddle to describe what Im trying to do and also the sample code where I am at so far https://jsfiddle.net/y6eoc0b4/
You can do this
var myTable = document.getElementById("myTable");
var rows = myTable.getElementsByTagName("tr");
console.log(rows);
var output = [];
for(var i = 0; i< rows.length; i++){
var cells = rows[i].getElementsByTagName("td");
output.push(cells[0].innerText+" "+cells[1].innerText)
}
document.getElementsByClassName("output")[0].innerText = output;
https://jsfiddle.net/LyswLtf8/
JSfiddle based on your comment here
//step first: select items like this
var fisrstTdArr = document.querySelectorAll(".location table tbody tr td:first-child");
var secondTdArr = document.querySelectorAll(".location table tbody tr td:nth-child(2)");
// or like this
var fisrstTdArr2 = document.querySelectorAll("#myId tbody tr td:first-child");
var secondTdArr2 = document.querySelectorAll("#myId tbody tr td:nth-child(2)");
// or even shorter if you have only one table on the page
var fisrstTdArr3 = document.querySelectorAll("td:first-child");
var secondTdArr3 = document.querySelectorAll("td:nth-child(2)");
for (var i = 0; i<fisrstTdArr.length; i++) { // than loop
console.log ('select method 1, fisrts column: ' + fisrstTdArr[i].innerText); // and use
console.log ('select method 1, second column: ' + secondTdArr[i].innerText);
console.log ('select method 2, fisrts column: ' + fisrstTdArr2[i].innerText);
console.log ('select method 2, second column: ' + secondTdArr2[i].innerText);
console.log ('select method 3, fisrts column: ' + fisrstTdArr3[i].innerText);
console.log ('select method 3, second column: ' + secondTdArr3[i].innerText);
}
<div class='location'>
<table id="myId">
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>else</td>
<td>here</td>
<td>else</td>
<td>here</td>
</tr>
</tbody>
</table>
</div>
This is a fixable code that can work on a table with any number of columns and any number of rows.
var table = document.querySelector('#my-table'),
trs = table.querySelectorAll('tr'),
outputDiv = document.querySelector('#output') ,
tds = [],
i, j,
output = '';
for (i = 0; i < trs.length; i += 1) {
tds = trs[i].querySelectorAll('td');
output += "Row #" + (i + 1) + "<br>";
for (j = 0; j < tds.length; j += 1) {
output += tds[j].innerText + ' ';
}
output += '<br>-----------------<br>';
}
outputDiv.innerHTML = output;
<table border=1 id="my-table">
<tr>
<td>Row1-Column1</td>
<td>Row1-Column2</td>
<td>Row1-Column3</td>
<td>Row1-Column4</td>
<td>Row1-Column5</td>
</tr>
<tr>
<td>Row2-Column1</td>
<td>Row2-Column2</td>
<td>Row2-Column3</td>
<td>Row2-Column4</td>
<td>Row2-Column5</td>
</tr>
<tr>
<td>Row3-Column1</td>
<td>Row3-Column2</td>
<td>Row3-Column3</td>
<td>Row3-Column4</td>
<td>Row3-Column5</td>
</tr>
</table>
<br>
<span style="font-weight: bold">Desired Output:</span> "Row1-Column1 Row1-Column2, Row2-Column1 Row2-Column2, Row3-Column1 Row3-Column2"
<br>
<br>
<span>Output:</span> <div id="output"></div>
JSFiddle
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);
}
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);
}
I am using JavaScript to fetch some XML data and loop it in a table. However the TD elements won't separate to a new line.
Here is my HTML:
<div id="gData">
<table class="tftable" border="1">
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
<tr>
<td class="gDate"></td>
<td class="gGame"></td>
<td class="gHome"></td>
<td class="gDraw"></td>
<td class="gAway"></td>
</tr>
</table>
</div>
and here is my JS:
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sports.sport.leagues.league.events.event;
for (var i = 0; i < game_data.length; i++) {
$('#gData .gGame').append( '<td>' + game_data[i].homeTeam.name + ' vs ' + game_data[i].awayTeam.name + '</td> ');
$('#gData .gDate').append( '<td>' + game_data[i].startDateTime) + '</td>';
$('#gData .gAway').append( '<td>' + game_data[i].periods.period[i].moneyLine.awayPrice) + '</td>';
$('#gData .gHome').append( '<td>' + game_data[i].periods.period[i].moneyLine.homePrice) + '</td>';
$('#gData .gDraw').append( '<td>' + game_data[i].periods.period[i].moneyLine.drawPrice) + '</td>';
}
};
The data comes back fine from the loop but displays all the dates in one TD, all the Games in the next TD.
You must also create your tr tags dynamically. Here's what I would suggest:
First make sure your table has a thead and tbody.
<table id="my-table">
<thead>
<th>Date</th>
<th>Game</th>
<th>Home</th>
<th>Draw</th>
<th>Away</th>
</thead>
<tbody></tbody>
<table>
Then you can generate your rows dynamically and append them to the tbody element. To save on writing i'll just give an example that isin't based on your code.
var $trs = $(document.createDocumentFragment()), //reduce DOM reflows
data = [{ a:1, b:2, c:3 }],
i = 0,
len = data.length,
rowData, $tr;
for (; i < len; i++) {
rowData = data[i];
$tr = $('<tr>'); //create your row
//append cells, you can also create a function to encapsulate
//that repetitive logic
$tr.append($('<td>').addClass('yourClass').text(rowData.a));
$tr.append($('<td>').addClass('yourOtherClass').text(rowData.b));
$tr.append($('<td>').addClass('yetAnotherClass').text(rowData.c));
//append the tr to the document fragment
$trs.append($tr);
}
//append the document fragment to the tbody
$('#my-table > tbody').append($trs);
It's remarkable how even the simplest task can be butchered by jQuery...
var table = document.getElementById('gData').children[0],
tbody = table.tBodies[0];
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sprts.sport.leages.leage.events.event,
len = game_data.length, i, tr;
table.removeChild(tbody);
for( i=0; i<len; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].homeTeam.name));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].startDateTime));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.awayPrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.homePrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.drawPrice));
tbody.appendChild(tr);
}
table.appendChild(tbody);
};
And this HTML:
<div id="gData">
<table class="tftable" border="1">
<thead>
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
Note that you can simplify the above code with a helper function:
function addCellWithText(tr,text) {
return tr.appendChild(document.createElement('td')).appendChild(document.createTextNode(text));
}
Then your loop's contents become:
for(...) {
tr = document.createElement('tr');
addCellWithText(tr,game_data[i].homeTeam.name);
addCellWithText(tr,game_data[i].startDateTime);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.homePrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.awayPrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.drawPrice);
tbody.appendChild(tr);
}
So I have this table, and when I click on a td I would like to know where is that(which row and cell) without any attributes on the elements.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td> // If I click on this I would like to know tr:1 & td:2
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
Javascript:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
// Track my location;
// example: I'm in table row 1 and I'm the 2th cell of this row
}
}
In the handler, this is the table cell, so for the cell index do this:
var cellIndex = this.cellIndex + 1; // the + 1 is to give a 1 based index
and for the row index, do this:
var rowIndex = this.parentNode.rowIndex + 1;
Example: http://jsfiddle.net/fwZTc/1/
This script block will provide you the information you desire, by adding the information as properties to the cell and then accessing them in the onclick function:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
// Get all the rows in the table
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
//Get the cells in the given row
var cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// Cell Object
var cell = cells[j];
cell.rowIndex = i;
cell.positionIndex = j;
cell.totalCells = cells.length;
cell.totalRows = rows.length;
// Track with onclick
console.log(cell);
cell.onclick = function () {
alert("I am in row " + this.rowIndex + " (out of " + this.totalRows + " rows) and I am position " + this.positionIndex + " (out of " + this.totalCells + " cells)");
};
}
}
Well, When you have rowspan/colspan you can have a lot more fun, however, if the grid is regular, you can just determine your position from the index by doing:
row = Math.floor(i / rows);
column = i % columns;
Using "this" on cells table
function myFunction(x) {
var tr = x.parentNode.rowIndex;
var td = x.cellIndex;
document.getElementById("tr").innerHTML = "Row index is: " + tr;
document.getElementById("td").innerHTML = "Column index is: " + td;
}
tr, th, td {
padding: 0.6rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td onclick="myFunction(this)">1</td>
<td onclick="myFunction(this)">2</td>
<td onclick="myFunction(this)">3</td>
</tr>
<tr>
<td onclick="myFunction(this)">4</td>
<td onclick="myFunction(this)">5</td>
<td onclick="myFunction(this)">6</td>
</tr>
<tr>
<td onclick="myFunction(this)">7</td>
<td onclick="myFunction(this)">8</td>
<td onclick="myFunction(this)">9</td>
</tr>
</tbody>
</table>
<p id="tr"></p>
<p id="td"></p>