jquery adding columns based on database records - javascript

I have an sqlite table with these columns:
| date | weight | bmi | mood | etc.
I want a table on my html page to display like this on the html page:
<table>
<caption></caption>
<thead>
<tr>
<td>(empty cell over row headings)</td>
Additional tH's as needed (this is where each date entry goes)
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Weight</th>
additional tD's as needed (this is where each weight entry goes matched with date in column heading)
</tr>
<tr>
<th scope="row">BMI</th>
additional tD's as needed (same as above)
</tr>
</tbody>
</table>
so basically I'm flipping the rows and columns for display purposes. This is all so I can graph the table using jQuery Visualize plugin that goes out as the date progresses. As you can imagine, over time more entries will be made adding to the columns of the display table. Here is what I have been messing around with so far (not including the graphing scripts ). I've gotten myself totally confused and now I'm just a mess...
Any suggestions would be a big help. I think I'm running into problems when trying to insert data into a table that's also trying to insert itself. I'm probably going about this wrong I bet.
Thanks
Mike
function homeSuccess(tx, results) {
// Gets initial count of records in table...
var entries = results.rows.length;
// Iterates over all the existing records...
for (var i = 0; i < entries; ++i) {
// The following element id's can be found in the div's within the table below, see element.innerHTML line...
var element = document.getElementById('colDate');
element.innerHTML += '<th scope="col">' + results.rows.item(i).timeStamp + '</th>';
var element2 = document.getElementById('tdWeight');
element2.innerHTML += '<td>' + results.rows.item(i).weight + '</td>';
var element3 = document.getElementById('tdBmi');
element3.innerHTML += '<td>' + results.rows.item(i).bmi + '</td>';
};
// 'screenView2 is a placeholder on the main html page...
var element = document.getElementById('screenView2');
element.innerHTML = '<br /><br /><h1>Data:</h1><br />Number of entries: ' + entries + '<br />' + '<table><caption>Mikes Health</caption><thead><tr><td></td><div id="colDate"></div></tr></thead><tbody><tr><th scope="row">Weight</th><div id="colWeight"></div></tr><tr><th scope="row">BMI</th><div id="colBmi"></div></tr></tbody></table>';
// This section is just a test trying to plug in static elements prior to trying database data... When using this section I had the iteration section commented out.
var element2 = document.getElementById('colDate');
element2.innerHTML = '<th scope="col">4-1-13</th>';
var element3 = document.getElementById('colWeight');
element3.innerHTML = '<td scope="col">123</td>';
var element4 = document.getElementById('colBmi');
element4.innerHTML = '<td scope="col">321</td>';
}
function homeQuery(tx) {
console.log("entering homeQuery");
tx.executeSql('SELECT * FROM HEALTHGRAPH', [], homeSuccess, onSqlError);
console.log("leaving homeQuery");
}
// Function that is called on initial page load
function homeDBopen() {
console.log("opening db for home data");
theDB = window.openDatabase("hgDB", "1.0", "HealthGraph", 3 * 1024 * 1024);
theDB.transaction(homeQuery, onTxError, onTxSuccess);
console.log("leaving homeDBopen");
}

Thought for sure someone would have answered this question as it seems like an issue lots of people must run into. A little discouraging. Anyway, I found an answer that I can adapt to my own project here:
http://msdn.microsoft.com/en-us/library/ie/ms532998(v=vs.85).aspx
// Insert cells into the header row.
for (i=0; i<heading.length; i++)
{
oCell = oRow.insertCell(-1);... etc.

Related

Loop through all children of in a firebase database key

i have a webapp where i save some values from inputs to the firebase database with this line:
fire.database().ref('gamehomeitems').push( dataset );
the dataset includes a "category", "value1" and "value2".
on another page, i want to render all the children saved in the 'gamehomeitems' part of my firebase database, but im not able to loop through them and get their values
what would be the appropriate code to render the category of all the children in 'gamehomeitems'?
Thanks in advance for any help
This question has been asked many times before and is covered in the documentation for Working with Lists of Data. But here is a bundled example of one way to achieve what you want.
Assuming this is your table:
<table style="width:100%" id="gamehomeitems-table">
<tr id="gamehomeitems-headerrow">
<th>Category:</th>
<th>Home Team:</th>
<th>Away Team:</th>
</tr>
</table>
<!-- at the bottom of the body -->
<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-database.js"></script>
<script>
firebase.initializeApp(/* ... */);
const gameHomeItemsRef = firebase.database().ref("gamehomeitems");
const gameHomeItemsTbl = document.getElementById("gamehomeitems-table");
const gameHomeItemsQuery = gameHomeItemsRef.orderByKey().limitToLast(20); // get 20 most recent entries
const gameHomeItemsChildAddedCallback =
gameHomeItemsQuery
.on('child_added', function(snapshot, keyOfPreviousRow) {
const rowData = snapshot.val();
let rowContent = '<tr id="item-' + snapshot.key + '">';
rowContent += "<td>" + rowData.category + "</td>";
rowContent += "<td>" + rowData.value1 + "</td>";
rowContent += "<td>" + rowData.value2 + "</td>";
rowContent += "</tr>";
gameHomeItemsTbl.append(rowContent);
// todo: make sure this row is inserted above the row for "keyOfPreviousRow" if newest at the top is required.
// currently it will be oldest at the top, newest at the bottom
});
const gameHomeItemsChildChangedCallback =
gameHomeItemsQuery
.on('child_changed', function(snapshot, keyOfPreviousRow) {
// todo: find row with id "item-KEY" and update it's data in the table
});
const gameHomeItemsChildRemovedCallback =
gameHomeItemsQuery
.on('child_removed', function(snapshot) {
// todo: find row with id "item-KEY" and remove it from the table
});
// later, when you no longer need the table to be updated live
// gameHomeItemsRef.off("child_added", gameHomeItemsChildAddedCallback);
// gameHomeItemsRef.off("child_changed", gameHomeItemsChildChangedCallback);
// gameHomeItemsRef.off("child_removed", gameHomeItemsChildRemovedCallback);
// todo: implement "child_moved" when not using orderByKey()
</script>

Jquery delete elements that were created using .after

I have a table in my html file which has the column header hard-coded:
<table id="debugger-table">
<tr>
<th>Attribute</th>
<th>Computed</th>
<th>Correct</th>
</tr>
</table>
Which I populate with values for row 2 onwards in a .js file using jquery:
tableString = '';
DEBUG_DATA.forEach(function(debug_line){
tableString += '<tr><td>' + debug_line['attribute'] + '</td><td>' + debug_line['computed'] + '</td><td>' + debug_line['correct'] + '</td>'
});
$('#debugger-table tr:last').after(tableString);
When the user performs a certain action I want to update the values. My question is how do I remove the text I've added, so that I can replace it with new text, instead of just appending the new values after the old ones.
I figure I could destroy the whole table and then create a new one with the column headers. Seems overkill though. Is there a way to refer back to the text added with .after, and delete it? thanks.
Store the addition into a jQuery object:
const rows = $(tableString);
('#debugger-table').append(rows); // Tip: this is better than
// $('#debugger-table tr:last').after(rows);
Then later remove it when needed:
rows.remove();

Get one specific row in automatically generated table

I am building a web application for the school. And I need to populate a table with data from a database. To do so, I used the following javascript :
http.onload = function (){
var roomData = JSON.parse(this.response);
roomData.forEach(data => {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
});
console.log((roomData));
}
http.open('GET', url, true);
http.send();
With the following architecture for the table :
<table class="table table-bordered">
<thead>
<tr>
<th>Address</th>
<th>Size</th>
<th>Price</th>
<th>Available</th>
</tr>
</thead>
<tbody>
</tbody></table>
But then, when I try to access one specific data with javascript, for example the price, I cannot really make the distinction between the rows because they have all the same id. Here is the code I am using to get the row's price :
$('td.price').html());
But obviously it only returns the price of the first row and not the one I want. How can I do it ?
You can achieve it as below:
Add the index in your forEach and use it as Id of the row:
roomData.forEach(function (element, index) {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td id="pricerow' + index + '" class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
$('#pricerow1').html());
$('#pricerow2').html());
Ok I finally figured how to do it, I used :
var rows = document.getElementsByTagName('tr');
console.log(rows[$(this).closest("tr").index()+1].cells[2].innerHTML);
Your 'roomdata' info should have an ID of some sort, which you can use as an ID on the . Like (roomdata ID 5), en then access it with $('#rd-5 td.price').
Not sure if I understand you correctly, but that's the easiest way. Always have an unique reference and work with ID's.

Adding color to particular cell in table by its id

function grid(rows, cols) {
var table = "<table id = \"myTable\">";
var size = (1 / rows * 525) + "px";
for (i=0; i<rows; i++) {
table += "<tr>";
for (j=0; j<cols; j++) {
var ID = i+','+j;
table += "<td id = \"ID\" >"+"</td>";
}
table += "</tr>";
}
table += "</table>";
var ID2 = randomFunction(rows, cols);
alert(ID2);
document.ID2.style.color = "red";
//document.getElementById(ID2).style.color = "#ff0000";
//table1.rows[1].cells[0].style.backgroundColor = "#003F87";
//id.style.backgroundColor='#003F87';
$("#container").empty().append(table);
}
I have generated table dynamically in javaScript specifying number of rows and columns. I have given id to each cell. I need to change the color of particular cell whose id is generated by random function. I tried in different ways but no solution.
One by one:
document.getElementById(ID2).style.color = "#ff0000";
won't work, because at this moment, the table is not in the dom, so document.getElementById(ID2) will return nothing.
table1.rows[1].cells[0].style.backgroundColor = "#003F87";
won't work, because table is a regular string, and strings don't have a rows property.
id.style.backgroundColor='#003F87';
won't work because id is again, a simple string. What would work is, to add the table to the dom first, using $("#container").empty().append(table);, and then do the setting of the color, using straightforward
document.getElementById(ID2).style.backgroundColor = "#ff0000";
or with jquery:
$("#"+ID2).css({backgroundColor: "#ff0000"}).
I would also recommend inserting a space ( ) in the table cells (note that your current code is incorrect, it sets the id for all the cells to the string "ID"), using
table += '<td id = "'+ID+'"> </td>';
otherwise the table could be rendered a little odd. Also id in the format 1,2 might cause problems, how about
var ID = 'td_'+i+'_'+j;
which gives you an ID like td_1_2, which won't mess up any browser.

show js array in html table

I have a javascript array and I want to show parts of it in HTML.
For example what html code would I use in the body to show a table of just the info from QR4 - the number and the country? There are other parts to the array so to show the whole QR4 array would be fine, but Id also like to know how to select specific parts
QR4[25] = "China";
QR4[24] = "39241000";
QR8[25] = "China";
QR8[24] = "39241000";
QR8L[25] = "China";
QR8L[24] = "39241000";
QR4L[25] = "China";
QR4L[24] = "39241000";
I have this code making a table in php using csv which works fine but I want it client side, not server side. A table like this would be fine...
<?php
echo "<table>\n\n";
$f = fopen("csv.csv", "r");
while (!feof($f) ) {
echo "<tr>";
$line_of_text = fgetcsv($f);
echo "<td>" . $line_of_text[10] . "</td>";
echo "<tr>\n";
}
fclose($f);
echo "\n</table>";
?>
Here is a really simple example of how you could do it.
Check this fiddle.
You have to pass an array to the function displayArrayAsTable(). You can then specify the range of the array to insert into the table, for example from 24 to 25 like you asked, otherwise all the array will be processed.
The function will return a table element you can then append where you find more appropriate, or tweak the function so that will always insert it for you where you want.
To show all rows of the QR4 array in a HTML table use this:
<table>
<tr>
<th>ID</th>
<th>City</th>
</tr>
<script type="text/javascript">
for(id in QR4)
{
document.write('<tr><td>' + id + '</td><td>' + QR4[id] + '</td></tr>');
}
</script>
</table>
To show specific elements from the Javascript array in a HTML table use this:
<table>
<tr>
<th>Number</th>
<th>City</th>
</tr>
<script type="text/javascript">
document.write('<tr><td>' + QR4[24] + '</td><td>' + QR4[25] + '</td></tr>');
</script>
</table>
As I suspect you want to combine the QR[24] and QR[25] elements in one row, that's what I did in my second code sample. But if that's the situation, your array structure isn't very logical.
I gave you the code samples to select data from Javascript arrays and put them in HTML tables, now it's on you to use it the way you need it.. Because that isn't clear to me at all..
Assuming you already have the table defined, you can use some simple DOM methods to add and delete rows.
var table = document.getElementById("mytable");
for(i=0; i < QR4.length;i++) {
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
cell.innerHTML = QR4[i];
}

Categories