How to convert HTML table to Javascript - javascript

So as a beginner, I have no idea how to create a table using Javascript. I can make a table using a simple html file but not in Javascript.
The output should have 2 columns and 4 rows. I also need to use the prompt tag in order to insert data for the second column. Not to mention that I need to average the total number in the 2nd column.
I tried searching but I got mixed results and its confusing me.so please help me
this is the html file
<html>
<body>
<table border="1" style="width:30%">
<tr>
<td>Rose</td>
<td>40</td>
</tr>
<tr>
<td>Daisy</td>
<td>50</td>
</tr>
<tr>
<td>Orchids</td>
<td>60</td>
</tr>
<tr>
<td>Flowers</td>
<td>150</td>
</tr>
</table>
</body>
</html>

Try this - >
var Rose = prompt("Enter price for Rose?");
var Daisy = prompt("Enter price for Daisy?");
var Orchids = prompt("Enter price for Orchids?");
var flowers = Number(Rose) + Number(Daisy) + Number(Orchids);
var table = document.createElement("table");
createTable();
function createTable(){
createTrTds("Rose",Rose);
createTrTds("Daisy",Daisy);
createTrTds("Orchids",Orchids);
createTrTds("Total",flowers);
document.getElementById("table").appendChild(table);
}
function createTrTds(text,value){
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var txt1 = document.createTextNode(text);
var txt2 = document.createTextNode(value);
td1.appendChild(txt1);
td2.appendChild(txt2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
td
{
border: 1px solid black;
}
<div id="table">
</div>

You will be helped by using a framework for this, jquery or angularjs comes to mind to solve it. However the pure JavaScript way looks like this:
This will create a table with inputs for the number of flowers and sum them up at the bottom when numbers change, you can also add more flower types in the JavaScript file.
var tabledef = [];
tabledef['Rose'] = 40;
tabledef['Daisy'] = 50;
tabledef['Orchids'] = 60;
writeTable();
function writeTable() {
var table = '<table border="1" style="width:30%">';
var sum = 0;
for (var i in tabledef) {
sum = sum + tabledef[i];
table = table + '<tr><td>' + i + '</td><td><input id="' + i + '" onchange="recalculate(this)" type="number" value="' + tabledef[i] + '"></td></tr>';
}
table = table + '<tr><td>Flowers</td><td>' + sum + '</td></tr></table>';
document.getElementById('myTable').innerHTML = table;
}
function recalculate(box) {
tabledef[box.id] = box.valueAsNumber;
writeTable();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myTable"></div>
<script src="createTable.js"></script>
</body>
</html>

You just need array with data and then fill table as thought it was an html document
var table = '<table border="1">',
data = [['Rose','Daisy','Orchids','Flowers'],[40,50,60,150]];
for (var i = 0; i < data[0].length; i++) {
table += '<tr>';
for (var j = 0; j < data.length; j++) {
table += '<td>' + data[j][i] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('container').innerHTML = table;
http://jsfiddle.net/5pdac6sb/

Related

Make an html table using a JSON object

I know there are a lot of similar questions out there. This code is a Frankenstein of a lot of other stack overflow questions. But I am so close I just don't understand the code I've been trying to use an examples very well.
Here is my html page:
<!DOCTYPE html>
<html>
<script src="Scripts.js"></script>
<script>
</script>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>
<body>
<p id="demo"></p>
<script>
obj.Blades.forEach(element => {
var name = element.Name + " " + element.Damage;
document.write(name + "<br >");
});
</script>
<input type="button" value="Generate Table" onclick="makeTable()" />
<hr />
<div id="dvTable"></div>
</body>
</html>
And here is the Java Script page:
var jsonStuff = '{ "Blades" : [' +
'{ "Name":"Longsword" , "Damage":"l2d" },' +
'{ "Name":"Dagger" , "Damage":"l3d" },' +
'{ "Name":"Mace" , "Damage":"l4d" },' +
'{ "Name":"Spear" , "Damage":"l5d" } ]}';
var obj = JSON.parse(jsonStuff);
function makeTable(){
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1"
//Get the count of columns.
var columnCount = Object.keys(obj.Blades).length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = obj.Blades[i].Name;
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < obj.Blades.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
console.log(obj.Blades[j].Damage);
var cell = row.insertCell(-1);
cell.innerHTML = obj.Blades[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
This is what it looks like right now:
So I know the problem has to be somewhere in the section of JavaScript commented "add the Data rows". I'm just now sure how to go about it.
I believe your problem is with the line:
cell.innerHTML = obj.Blades[i][j];
You are referring to Blades as if it were a 2-dimensional array, when in fact it is an array of objects. You're going to need to have something like this to avoid the undefined:
cell.innerHTML = obj.Blades[i].Name;
cell.innerHTML = obj.Blades[i].Damage;

javascript table format output

I have this JavaScript html code for getting the tabular format output. I am giving XML data as input to the script.
function myFunction() {
parser=new DOMParser();
xmlDoc=parser.parseFromString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"<book>"+
"<title>The Time Machine and Other Stories</title>"+
"<author_name>H. G. Wells</author_name>"+
"<publish_date>2016</publish_date>"+
"<cost currency=\"USD\">10</cost>"+
"<publisher_info>"+
"<publisher_name>Read Books Ltd</publisher_name>"+
"<publisher_address>"+
"<street_name>Evesham street</street_name>"+
"<city>Worcestershire</city>"+
"<zip_code>11WR</zip_code>"+
"<country>United Kingdom</country>"+
"</publisher_address>"+
"</publisher_info>"+
"</book>","text/xml");
var x=xmlDoc.getElementsByTagName("publisher_address");
for (i=0;i<x.length;i++) {
document.write("<tr>");
var y=x[i].childNodes;
for (j=0;j<y.length;j++) {
document.write("<td>"+ y[j].childNodes[0].nodeValue+ "</td>");
}
document.write("</tr>");
}
}
table, th, td {
border: 1px solid black;
}
<h1>My First XML Parsing JavaScript</h1>
<p>Click the button to display book info.</p>
<p id="demo"></p>
<button type="button" onclick="myFunction()">Try it</button>
<table border="0">
</table>
The output I am getting is:
Evesham streetWorcestershire11WRUnited Kingdom
Can anyone help me why I am not able to get output in tabular format?
You are using document.write()which does not gives you expected output.
Use createElement to create a table, fill the data by creating rows, and td's and append to your dom or your paragraph.
<!DOCTYPE html>
<html>
<head>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>My First XML Parsing JavaScript</h1>
<p>Click the button to display book info.</p>
<p id="demo"></p>
<button type="button" onclick="myFunction()">Try it</button>
<table border="0">
<script>
function myFunction() {
parser = new DOMParser();
xmlDoc = parser.parseFromString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<book>" +
"<title>The Time Machine and Other Stories</title>" +
"<author_name>H. G. Wells</author_name>" +
"<publish_date>2016</publish_date>" +
"<cost currency=\"USD\">10</cost>" +
"<publisher_info>" +
"<publisher_name>Read Books Ltd</publisher_name>" +
"<publisher_address>" +
"<street_name>Evesham street</street_name>" +
"<city>Worcestershire</city>" +
"<zip_code>11WR</zip_code>" +
"<country>United Kingdom</country>" +
"</publisher_address>" +
"</publisher_info>" +
"</book>", "text/xml");
// creating a table
table = document.createElement('table');
var x = xmlDoc.getElementsByTagName("publisher_address");
for (i = 0; i < x.length; i++) {
// create a row
var tr = table.insertRow();
var y = x[i].childNodes;
for (j = 0; j < y.length; j++) {
// crate a cell for your data
var td = tr.insertCell();
// put the data into your td
td.innerHTML = y[j].childNodes[0].nodeValue;
}
}
// append it to body, or to your p#demo
document.body.appendChild(table);
}
</script>
</table>
</body>
</html>
You need to give your table a container with an ID to hook to:
<table>
<tbody id="my-table-contents"></tbody>
</table>
Then in your javascript you can append to that container.
<script>
var myTable = document.getElementById('my-table-contents');
function myFunction() {
parser = new DOMParser();
xmlDoc = parser.parseFromString(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<book>" +
"<title>The Time Machine and Other Stories</title>" +
"<author_name>H. G. Wells</author_name>" +
"<publish_date>2016</publish_date>" +
"<cost currency=\"USD\">10</cost>" +
"<publisher_info>" +
"<publisher_name>Read Books Ltd</publisher_name>" +
"<publisher_address>" +
"<street_name>Evesham street</street_name>" +
"<city>Worcestershire</city>" +
"<zip_code>11WR</zip_code>" +
"<country>United Kingdom</country>" +
"</publisher_address>" +
"</publisher_info>" +
"</book>", "text/xml");
var x = xmlDoc.getElementsByTagName("publisher_address");
for (i = 0; i < x.length; i++) {
myTable.innerHtml += "<tr>";
var y = x[i].childNodes;
for (j = 0; j < y.length; j++) {
myTable.innerHtml += "<td>" + y[j].childNodes[0].nodeValue + "</td>";
}
myTable.innerHtml += "</tr>";
}
}
</script>

How can I insert a <tr> element into a dynamic table?

I hope someone has a clue for me. I am new to javascript and I am trying to build this structure with a dynamically generated table.
<table>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td>value4</td>
</tr>
<tr>
<td>value5</td>
<td>value6</td>
<td>value7</td>
<td>value8</td>
</tr>
<tr>
<td>value9</td>
<td>value10</td>
<td>value11</td>
<td>value12</td>
</tr>
<tr>
<td>value13</td>
<td>value14</td>
<td>value15</td>
<td>value16</td>
</tr>
</table>
What I tried to do is to echo a <tr> after every 4th pair of <td>.
Like this:
var tbody_el = $("#somevalue_id"); //is the id of the table, which needs to be filled with `<tr>` and `<td>`.
var counter = 0;
$.each(TonsOfData.getValues(), function(index, somevalue) {
//var tr_el = $("<tr></tr>");
var td_checkbox_el = $("<td></td>");
var cbName = "cb_" + somevalue.displayName + "_name";
var cbId = "cb_" + somevalue.displayName + "_id";
var inputEl = $("<input type='checkbox' name='" + somevalue.displayName + "' id='" + cbId + "'/>");
inputEl.data("somevalueId", somevalue.id);
inputEl.attr("checked", "checked");
inputEl.change(valueChoicesClick);
var div_value_id = "div_value_" + somevalue.id + "_id";
var div_value_el = $("<div id='" + div_value_id + "' align='left'></div>");
var td_value = $("<td></td>");
td_checkbox_el.append(inputEl);
if(counter == 0 || (counter +1)%4 == 0){
echo "<tr>";
}
td_value.append(td_checkbox_el, "<br> Displayname: " + somevalue.displayName,"<br> Unit: "+ somevalue.unitstring," <br>",div_value_el);
if((counter +1)%4 == 0) {
echo "</tr>";
}
//tbody_el.append(tr_el);
}
);
Is this even possible?
Or am I going a totally wrong way?
Big thanks for any suggestions!!
EDIT:
I found a solution that worked for me. I doubt anyone will have the same issue, but I'd like to share it anyway.
I created a counter that gets incremented in the loop and gave the <td> parts a class-id.
if(counter<4){
td_value = $("<td class='select1'></td>");
}
if(counter>3 && counter <8){
td_value = $("<td class='select2'></td>");
}
if(counter>7 && counter <12){
td_value = $("<td class='select3'></td>");
}
if(counter>11 && counter <16){
td_value = $("<td class='select4'></td>");
}
if(counter>15 && counter <20){
td_value = $("<td class='select5'></td>");
}
After that I used the JQuery wrapAll()-function to add my <tr>. That did the trick.
$('#somevalue_id td.select1').wrapAll('<tr/>');
$('#somevalue_id td.select2').wrapAll('<tr/>');
$('#somevalue_id td.select3').wrapAll('<tr/>');
$('#somevalue_id td.select4').wrapAll('<tr/>');
$('#somevalue_id td.select5').wrapAll('<tr/>');
I know, it is not the most elegant solution but it works.
Thanks again to everyone that gave me hints, you helped me solve this!
You can use jquery and using .each for iterating and getting the fourth element in each iteration using .nth-child and inserting after using .insertAfter
Please find the example to mainuplate the table accordingly.
this is one way you can do it
<table class="test_table" id="test_table">
</table>
var tableEl = $(".test_table");
var noOfRows = 4;
var noOfColumns = 4;
//Empty the table in case there is anything already there
tableEl.each(function(){
var tableElObject = $(this);
for(i=0;i<noOfRows;i++)
{
rowStart = "<tr>";
for(j=0;j<noOfColumns;j++)
{
rowStart +="<td>"+"Test"+i+j+"</td>";
}
tableElObject.append(rowStart+"<tr/>");
}
});
http://jsfiddle.net/qg5hG/
if you want to create tables trs and tds dynamically this way can be better for you....
var table = document.createElement('table');
table.setAttribute('border','0');
table.setAttribute('cellspacing','5');
table.setAttribute('cellpadding','5');
table.setAttribute('width','100%');
var tr = table.insertRow(-1);// "-1"s meaning add tr to end of table if you want to add top of table you must use "0"
tr.id = 'Tr1 ID';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';
var tr = table.insertRow(-1);
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';

Apply different colors to Dynamically generated row of HTML table

I've created dynamic table using HTML and javascript but rather than applying alternate color, I want to apply distinct color to each row. How can I do so?
<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<table>
<tr>
<td>Enter Rows</td>
<td><input type="number" id="txtRows"/></td>
</tr>
<tr>
<td>Enter Columns</td>
<td><input type="number" id="txtCols"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" id="btnDisplay" value="Display" onClick="createTable();"/></td>
</tr>
</table>
<table id="tbl_DynamicTable" border="1">
</table>
</body>
<script type="text/javascript">
function createTable()
{
debugger;
var rows = document.getElementById("txtRows").value;
var cols = document.getElementById("txtCols").value;
var table = document.getElementById("tbl_DynamicTable");
var str="";
for(var i=0;i<rows;i++)
{
str += "<tr id=row" + i +">";
//r = document.getElementById('tbl_DynamicTable').getElementsByTagName('<tr>');
//r.bgColor = colours[(i%k)/group | 0];
//mycurrent_row.style.backgroundColor = "#EEF4EA";
//mycurrent_row.style.backgroundColor =colours[(i%k)/group | 0];
for(var j=0;j<cols;j++)
{
if(i==0)
{
str += "<th> Header " + j + "</th>";
}
else
{
str += "<td> Row " + i + ", Cell "+ j + "</td>";
}
}
str += "</tr>";
}
table.innerHTML = str;
}
$("tr").style("bgcolor","red");
</script>
</html>
I don't know how to use jQuery with HTML page. I'm new to this. So if possible please let me know what is needed to include in this too.
You have many way to create a random color.
Use these example :
JAVASCRIPT
'#'+Math.floor(Math.random()*16777215).toString(16);
jQuery
(function(m,s,c){return (c ? arguments.callee(m,s,c-1) : '#') +
s[m.floor(m.random() * s.length)]})(Math,'0123456789ABCDEF',5)
And add this hexa random color on your TR when you generate it
HTML
<table border="1">
<tr bgcolor="#FF0000">
^ Here
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
Other example on http://www.paulirish.com/2009/random-hex-color-code-snippets/
javascript approach (i suggest including jQuery):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
// paint rows on document ready
$(function(){
paint_rows();
});
function paint_rows() {
$('#table_id tr').each(function(){
$(this).css('color', get_random_color());
});
}
</script>
just make sure to add enough color values into the array colors (can use hex values as well).
and, you can call the function paint_rows() whenever needed of course.
hope that helps.

How to add image in table cell

Hi I want to add image in table cell according to condition in table. I am using dynamic table as follow:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Now I am checking condition as if (pra[i]=="Green") then I want to add image in cell insted of "Green" string and same for Red string. Any help will be appreciated. Thanks in advance.
instead of :
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
do
pra[i] = "<img id='theImg' src='../../jquery.mobile/images/up.png'/>";

Categories

Resources