I'm trying to create a table to show persisted highscores coming from a MySQL database. Though I have the data coming into the code (JSON format) I'm having trouble displaying it in a presentable way. I'm trying to append a table to the body with the highscore data. The number of rows will depend on how much data there is, but the number of columns will always be two.
$.ajax({
url : '../server.php',
type : 'GET',
success : function(response) {
var toAppend = '<table style="position: fixed; top:200px; left: 200px;" id="highscores">';
var jsonObject = eval(response);
var highscores = "";
for ( i = 0; i < jsonObject.length && i < 10; i++) {
highscores += jsonObject[i].Name + " " + jsonObject[i].Score + "\n";
toAppend += "<tr>";
toAppend += jsonObject[i].Name;
toAppend += "</tr><tr>";
toAppend += jsonObject[i].Score;
toAppend += "</tr>";
}
toAppend += "</table>";
$('body').append(toAppend);
alert(highscores);
},
error : function() {
alert("fail");
}
});
This is my code to receive the json data from the server which has taken the MySQL data and converted it into JSON. I have alerts in the code for debugging but this is not how I want to display the data. I want a new row on the table for every score and each row will have two columns. One for name and one for score.
You're appending rows for each value, instead of adding a row per object, then adding cells within.
Something more like this:
var toAppend = $('<table style="position: fixed; top:200px; left: 200px;" id="highscores"></table>');
var jsonObject = eval(response);
for ( i = 0; i < jsonObject.length && i < 10; i++) {
var newRow = $('<tr></tr>');
$('<td></td>').text(jsonObject[i].Name).appendTo(newRow);
$('<td></td>').text(jsonObject[i].Score).appendTo(newRow);
newRow.appendTo(toAppend);
}
$('body').append(toAppend);
Related
Having issues with what it might be a rather easy fix.
Context: My code is currently pulling data from Google Sheets, crafting some sort of table and sending it back to HTML where it repopulates an already existing table.
Issue: I am unable to make it so that it builds columns as well as rows. It pastes the data back all in one go (see image for context).
Files: GS & HTML. I believe the issue is on how I'm crafting the table. I know the current disposition of '' doesn't make sense, bu
HTML table with Gsheet values:
Original Gsheet table:
Google Script
function populateStratTb2(){
var tablerows = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(1, 5, 1000).getValue();
var tablevalues = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var active = SpreadsheetApp.getActive();
var sheet = active.getSheetByName("supp_str");
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for ( var r = 0; r < 10; r+=1) {
for (var i = 0; i < data.length; i+=1) {
optionsHTML += '<tr><td>' + data[i][r] + '</td></tr>';
}};
return optionsHTML;
}
HTML Script
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(displayData)
.populateStratTb2();
});
function displayData(hl){
document.getElementById('strattable').innerHTML=hl;
}
console.log('MyCode');
</script>
PS. I have spent a good couple hours scrolling though the forum picking bits and improving my original code. I am sure this question (or similar) has been answered already but I can't manage to find it.
In your script, how about the following modifications?
Modification 1:
If your for loop is used, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for (var r = 0; r < 10; r += 1) {
var row = "";
for (var i = 0; i < data.length; i += 1) {
row += '<td>' + data[i][r] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
return optionsHTML;
}
I'm worried that your for loop might not be your expected result. So, I would like to proposed one more modified script as "Modification 2".
Modification 2:
If your data is converted to the HTML table, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
return optionsHTML;
}
Note:
If you don't want to add the border, please modify <table border="1" style="border-collapse: collapse"> to <table>.
From your reply, I added 2 sample scripts for the script for obtaining the same result from reduce and for loop as follows.
reduce
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
for loop
var optionsHTML = "";
for (var r = 0; r < data.length; r++) {
var row = "";
for (var c = 0; c < data[r].length; c++) {
row += '<td>' + data[r][c] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
Reference:
reduce()
I am trying to work on electron and made a simple dashboard GUI. i am a beginner in node js and electron.
Problem:
in my main gui.html: i have a table is being loaded, and from that table i need to select the rows from checklist for which i have made a js script:
script in read_checklist.js, this is taking the input checkbox element and selecting the whole row, which will later be shown after some processing in the textarea.
var checkboxes = document.getElementsByTagName("input");
var select_all = document.getElementById("allcb");
var warn_code = Array();
var family_array = Array();
var fail_drive_array = Array();
var waiverMap = {};
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var Warn_Code = currentRow.getElementsByTagName("td")[0];
var Family = currentRow.getElementsByTagName("td")[1];
var failing_drive = currentRow.getElementsByTagName("td")[3];
warn_code.push(Warn_Code.textContent);
family_array.push(Family.textContent);
fail_drive_array.push(failing_drive.textContent);
console.log('server started!' + currentRow );
alert(currentRow.textContent);
};
}
I am trying to import this in my gui.html like this:
This is where the table is getting displayed (code for this is below and it is stored in the renderer.js)
<!--This is for the table-->
<div id="data_lib" class="table-responsive">
</div>
<script type="text/javascript" src="./read_checklist.js"></script>
<!--This is for the table-->
My table is coming from another file, renderer.js
$(document).ready(function(){
var data;
$.ajax({
type: "GET",
url: "/Users/mrimat01/Desktop/CODE/electron_QAB_GUI_main/GUI/data.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
generateHtmlTable(data);
}
});
function generateHtmlTable(data) {
var html = "<table id='big_tables' class='table table-striped table-bordered' method='GET'>";
if(typeof(data[0]) === 'undefined') {
return null;
} else {
$.each(data, function( index, row ) {
//bind header
if(index == 0) {
html += '<thead>';
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<th>';
html += colData;
html += '</th>';
});
html += '<th>';
html += "<input type='checkbox' id='allcb' name='allcb'/>Select";
html += '</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
} else {
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<td>';
html += colData;
html += '</td>';
});
html += '<td>';
html += "<input id='name' type='checkbox' name='name' value='name' /> ";
html += '</td>';
html += '</tr>';
}
});
html += '</tbody>';
html += '</table>';
$('#data_lib').append(html);
}
}
});
I can see the table getting generated but read_checklist.js desn't work.
If i try to do the same thing in console, it works perfectly.
i have gone through many SO answers but couldn't seem to make this work.
Things i have tried:
making node_integration: true
using
module = undefined;}</script>
<script>if (window.module) module = window.module;</script>
adding the script directly below root <div>
I have been able to successfully read in a CSV file from a URL, parse through it, and write it out to a table. Simple to most but a Herculean effort for me. There is a header row, and each row contains 4 values (the first will be disregarded).
What I need to do is to be able to write each row to a different place on my page at will. I assume to do this I'd need to load each row into a slot in an array, where I can then call them specifically. For example if I want the 3rd entry, and also be able to access each value to build my text string, it would have to look something like:
document.getElementById("snow").innerHTML = 'Trail Status: ' + trail[2].status + 'Report Date: ' + trail[2].reportDate;
I know that the above code probably is flawed, but it was more illustrative than anything.
What I don't know how to do is setup an array to hold each row (so they can be accessed individually), define each value so it can be a accessed (trail, reportDate,etc), and read the CSV properly into that array.
I'm currently using jQuery and the code below to read, parse, and create the table.
$.ajax({
url: 'https://data.import.io/extractor/...',
dataType: 'text',
}).done(successFunction);
function successFunction(data) {
var allRows = data.split(/\r?\n|\r/);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th>';
table += rowCells[rowCell];
table += '</th>';
} else {
table += '<td>';
table += rowCells[rowCell];
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
table += '</tbody>';
table += '</table>';
$('body').append(table);
}
Any direction to reaching my end state would be greatly appreciated. Ultimately I'm building a dashboard that will show the Trail Conditions (from the CSV) and 10-day weather forecast (from Wunderground) to help plan Snowmobile Trips for local Michigan snowmobilers.
Thanks!
Marc
Create a multidimensional array - with 2 dimensions. The first index will access each row. The second index will access each cell within a row.
This reference may help: https://trans4mind.com/personal_development/JavaScript/Array2D.htm
This is an example using your current for loops.
function successFunction(data) {
var parsedData = [];
var allRows = data.split(/\r?\n|\r/);
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
parsedData[singleRow][rowCell] = rowCells[rowCell];
}
}
}
Thanks for the input, i found that PapaParse was the way to go! The data was easy to get at and I had no problems!
I'm working on a small project, I was asked to create a small splash table. In the splash table they want to know if one of the services in a server is online or not(since not everyone has access to the servers). so I was ask to create a html table from a CVS in which I accomplish by using the code below
< script type = "text/javascript" >
$.get('test3.csv', function(data) {
var build = '<table>\n';
var rows = data.split("\n");
rows.forEach(function getvalues(thisRow) {
build += "<tr>\n";
var columns = thisRow.split(",");
for (var i = 0; i < columns.length; i++) {
build += "<td>" + columns[i] + "</td>\n";
}
build += "</tr>\n";
})
build += "</table>";
$('#container').append(build);
});
<div id="container"></div>
it creates the table and everything is fine with the code. but what I need is to "replace" the X that are alone with an image like a green bubble.
the CVS file is set-up like this:
IP, Server Name, Function1, function2, function3
000000, Test1, X,,,
If anyone could, it would be appreciate.
Thanks
Make a function that checks if the column value is "X" and returns the image. Something like replaceValueX(columns[i]) and then the function just has something like
$.get('test3.csv', function(data) {
var build = '<table>\n';
var rows = data.split("\n");
rows.forEach(function getvalues(thisRow) {
build += "<tr>\n";
var columns = thisRow.split(",");
for (var i = 0; i < columns.length; i++) {
build += "<td>" + replaceValueX(columns[i]) + "</td>\n";
}
build += "</tr>\n";
})
build += "</table>";
$('#container').append(build);
});
function replaceValueX(columnValue) {
if(columnValue == "X"){
return "<img src='greenbubble.png'>";
}else {
return columnValue;
}
}
I want print a table dynamically, but my program displayed in a messy way.
I hope each row conludes two elements. I want to display the table like this. In 1s it gets a name and display it. And in next 1s it gets another name and display it. By repeating in this way, display all data.Here is my main code.
var count = 0;
function AddTd(id, showname)
{
console.log(id);
if(id == 0) // if this is in the first column
{
var str = '<tr><td width="10px">'+showname+'</td>';
$("#datashow").append(str);
count = 1; // next element should in second column
return;
}
if(id == 1) // if this is in the second column
{
var str = '<td width="10px">'+showname+'</td></tr>';
$("#datashow").append(str);
count = 0; // next element should in first column
return;
}
}
setInterval('change()',50); // In function change, print the table dynamically
This should create table with as many elements as there will be in array and do 2 columns per row.
http://jsfiddle.net/XfKME/3/
var names = ["name1", "name2", "name3", "name4"];
var tbody = "<table>";
$.each(names, function (i, item) {
if (i % 2 == 0)
tbody += "<tr>";
tbody += "<td>";
tbody += item;
tbody += "</td>"
if (i % 2 == 1)
tbody += "</tr><br />";
});
tbody += "</table>";