Make an html table using a JSON object - javascript

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;

Related

Creating button in modal dialogue and run code in spreadsheet

I making a table and show it in the modal dialogue so that buttons will appear for each row in the table. My question is how to make the button in the modal dialogue run for specific row in spreadsheet? Example : click first button in first row in modal dialogue, will run and change data in first row of spreadsheet. Do I need to create specific ID for each buttons?
My GS code:
function leadRespond(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var dataRange = sheet.getDataRange();
var dataValue = dataRange.getDisplayValues();
var temp = HtmlService.createTemplateFromFile("lead");
temp.data = {application : dataValue};
var html = temp.evaluate().setWidth(1200).setHeight(600);
SpreadsheetApp.getUi().showModalDialog(html,"Manage Leave");
}
HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Leave Application</h1>
<div id="output"></div>
<script>
var output = document.getElementById("output");
window.onload = function (){
google.script.run.withSuccessHandler(onSuccess).getTable();
}
function onSuccess(data){
if(data.success){
console.log(data.data);
var html = '<table>';
var row;
for(var i=0; i<data.data.length; i++){
html += '<tr>';
row = i;
//console.log(row);
for (var j=0; j<9; j++){
html += '<td>'+ data.data[i][j]+'</td>';
}
html += '<td>'+ '<button onclick="approve()">Approved</button>'+'</td>';
html += '</tr>';
}
html += '</table>';
output.innerHTML = html;
console.log(data);
}
}
function approve(){
google.script.run.getRow();
console.log("test");
}
</script>
</body>
</html>
Code with google.script.run :
function getTable(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var data = sheet.getDataRange().getDisplayValues();
Logger.log(data);
return {'success': true,'data':data};
}
function getRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
for (var i=0; i<dataValue.length; i++){
var row = "";
var rowNum;
for (var j = 0; j < 9; j++) {
if (dataValue[i][j]) {
row = row + dataValue[i][j]; //row = "" + range(0,0) [emailAddress], row = range(0,0)+ range(0,1)[emailAddress,Timestamp]
}
row = row + ",";
}
row = row + " Row num " + i;
rowNum = i;
Logger.log(row);
Logger.log(rowNum);
}
}
Use custom html-data attributes and delegate event to <table>:
html += '<td>'+ '<button data-row="'+i+'" data-column="'+j+'">Approved</button>'+'</td>';
//...
output.innerHTML = html;
console.log(data);
const table = document.querySelector("table");
table.addEventListener('click', approve);
}
function approve(e){
const td = e.target;
const [row, column] = [td.dataset.row,td.dataset.column];
google.script.run.modifyRows(row,column);
}

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 dynamically add to html table using javascript Json

This is my code how to dynamically add the html table do not use Jquery. Only use html and javascript. this code was server to client application this client receive the Json object to parse in string . how to add html table.
## <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="E:\vj\SignalR\json_js\json.js"></script>
<script src="E:\vj\SignalR\json_js\json2.js"></script>
<script src="E:\vj\SignalR\json_js\bson\bson.js"></script>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8100");
var received_msg;
var Dictionary=new Dictionary();
var globalSymbol;
function WebSocketTest()
{
ws.onerror = function ()
{
alert("error");
};
ws.onopen = function ()
{
alert("Client Connected");
ws.send("New1");
};
ws.onclose = function ()
{
alert("Connection is closed...");
};
ws.onmessage=function(evt)
{
var msg=evt.data
alert(msg);
var jsn=JSON.parse(evt.data);
//var text =('{"newQuote":' + jsn);
var tbl = document.getElementById('_table_Quote_ID');
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow)
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = jsn[0].symbol;
cell2.innerHTML = jsn[1].bid;
cell3.innerHTML = jsn[2].ask;
cell4.innerHTML = jsn[3].high;
cell5.innerHTML = jsn[4].low;
First of all, I understand this you say 'how can I create dynamic table ' , I hope this code can fix your problem
<script>
var length = 5 // this is your data lenght i write 5 for examples
var table = "<table border = '1' cellpadding='10'>";
for (var i = 0 ; i < length ; i++) {
table += "<tr>";
for (var j = 0 ; j < length ; j++) {
table += "<td> value </td>";
}
table += "</tr>";
}
table += "<table>";
document.write(table);
</script>

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/

problems trying to get tweets from different zip codes

I am trying to get tweets from different zip codes.For doing this, I am using latitude and longitude values for each zip code. So far I want to get 3 tweets for each zip code(I have 2 zip codes), but it is working only for one zip code.
Any suggestion will be appreciated. Thank you in advance!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat=[41.9716,42.0411];
var lng=[-87.7026,-87.6900];
$(document).ready(function() {
for(var i=1; i<2; i++)
{
$.getJSON('http://search.twitter.com/search.json?q=business&geocode='+lat[i]+','+lng[i]+',5mi&lang=en&callback=?', function(data) {
var data = data.results;
var html = "";
for(var j=0; j<3;j++){
html += "<div style='width:600px;border:solid thin blue'><img src='"+data[j].profile_image_url+"'/><a href='http://twitter.com/" + data[j].from_user + "'>#"+ data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content'+i).html(html);
}); }
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
I found 2 problems with your code:
1) If you want to iterate 2 times, your for function should be like this: for (var i = 0; i < 2; i++)
2) You must have in consideration that the function that gets called in $.getJSON runs asynchronously, so when that function gets called the for will have already finished, therefore you can't use the i value with that purpose inside that function.
So, after correcting those 2 things in your code you should be able to get what you want. Try with something like this:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat = [41.9716, 42.0411];
var lng = [-87.7026, -87.6900];
var count = 1;
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$.getJSON('http://search.twitter.com/search.json?q=business&geocode=' + lat[i] + ',' + lng[i] + ',5mi&lang=en&callback=?', function (data) {
var data = data.results;
var html = "";
for (var j = 0; j < 3; j++) {
html += "<div style='width:600px;border:solid thin blue'><img src='" + data[j].profile_image_url + "'/><a href='http://twitter.com/" + data[j].from_user + "'>#" + data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content' + count++).html(html);
});
}
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
</html>

Categories

Resources