javascript table format output - javascript

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>

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;

Table Issue in WYSIWYG Editor

I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
</head>
<body>
<div id="Ribbon">
<div id="Ribbon-3">
<button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
</div>
</div>
<div id="TextArea">
<div id="WYSIWYG" contenteditable="true"></div>
</div>
</div>
</body>
</html>
JS
window.addEventListener("load",function(){
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns");
var rownum = prompt("Indicate the number of rows");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i = 0; i < colnum; i++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
document.execCommand("insertHTML",false, table);
});
},false);
I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row
I've found the error. Such a dumb mistake...
I was using the same "i" var for the nested for loop and its parent loop.
This is the right version:
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns:");
var rownum = prompt("Indicate the number of rows:");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i1 = 0; i1 < colnum; i1++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
document.execCommand("insertHTML",false, table);
});

Converting CSV input in textarea to dynamic table

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>
You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

How to convert HTML table to 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/

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

Categories

Resources