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];
}
Related
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();
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.
Why do these two functions give different results?
var table1 = document.getElementById("table1");
var table2 = document.getElementById("table2");
var register = [
{att1: 1, att2: 2, att3: 3},
{att1: 4, att2: 5, att3: 6},
{att1: 7, att2: 8, att3: 9}
];
//table1.innerHTML = "";
//table2.innerHTML = "";
function drawTable1() {
for (var i = 0; i < register.length; i++) {
table1.innerHTML += "<tr><td>" + register[i].att1 + "</td><td>" + register[i].att2 + "</td><td>" + register[i].att3 + "</td></tr>";
}
}
function drawTable2() {
for (var i = 0; i < register.length; i++) {
table2.innerHTML += "<tr>";
table2.innerHTML += "<td>" + register[i].att1 + "</td>";
table2.innerHTML += "<td>" + register[i].att2 + "</td>";
table2.innerHTML += "<td>" + register[i].att3 + "</td>";
table2.innerHTML += "</tr>";
}
}
drawTable1();
drawTable2();
table {
display: inline;
}
<body>
<table>
<thead>
<tr>
<th>Att1</th>
<th>Att2</th>
<th>Att3</th>
</tr>
</thead>
<tbody id="table1">
</tbody>
</table>
<table>
<thead>
<tr>
<th>Att1</th>
<th>Att2</th>
<th>Att3</th>
</tr>
</thead>
<tbody id="table2">
</tbody>
</table>
</body>
I'm just beginning with js, and I've noticed this thing. From a logical point of view i see no differences between the two functions, the second has just been broken up to make the code easier to read. It should simply be adding strings to a string, but it seems like at every operation the opened tags get closed by the program, resulting in a multitude of rows.
Why is this? How is this useful?
innerHTML isn't actually a string. It's an interface to the DOM (the elements on the page); reading from it generates a string version of what's currently there, and assigning a value to it modifies the tree.
It's impossible to have an unclosed <tr> element in the DOM -- when you perform an operation like table1.innerHTML += "<tr>", the browser sees the unclosed <tr> tag as invalid HTML and has to repair it by inserting a closing </tr>. When you later access innerHTML to perform another modification, you see the "repaired" version, not the value you initially assigned.
The easiest fix will be to build the entire table as a string, then assign to innerHTML all at once, e.g.
var html = "";
for (...) {
html += "<tr>";
html += "<td>example</td>";
html += "</tr>";
}
table1.innerHTML = html;
You may also want to investigate Javascript DOM methods to create HTML elements (like document.createElement()) as an alternative -- innerHTML is a clumsy interface.
Well the innerHTML content is — as the name implies — HTML and HTML is not just a string. I assume you know that browsers build a DOM out of it. Basically a tree out of nodes that know their tag, attributes, children etc.
Now you need this DOM to render anything. Sure, it is nearly impossible to get invalid html as non-html can just be interpreted as a mere string (which is valid html). However, the browser tries to fullfill the html standard as much as possible. Therefore it also generates missing end tags in order to produce well-formed html. (even when it is not in the html, he will implicitely generate them for the DOM and in some browsers you can see that in the HTML provided in the dev console).
So now you add a random <tr> attribute to your html like this table2.innerHTML += "<tr>". This would produce not-well-formed html. Therefore it should generate the missing end tag. Whether that is done while running the js-code or afterwards when refreshing the DOM, I don't know, but generally it helps generate well-formed HTML.
I'm sure you know how to circumvent that problem, but anyways: Instead of using an temporary string, you might want to look at document.createElement(). This is generally used to generate well-formed html in a non-confusing and safe (as in "something unexpected like above doesn't happen safe") way.
I have html table on my parent page that has some data:
Begin Date End Date City
03/28/2017 Toronto
03/25/2017 03/26/2017 Miami
03/22/2017 03/24/2017 Chicago
03/16/2017 03/21/2017 Dallas
03/10/2017 03/15/2017 Austin
After use update the element from specific row I would like to replace entier content of that row. Each row had unique id. I have to do this with plain JavaScript Vanilla. Here is my example what I have so far:
fnObj.DATA is numeric and I get that after my ajax call is successfully completed. I use the id from that callback function to detect the row that I want to update. I'm not sure what is the best technique to replace all the td tags. This technique works with one exception. There is no id on the row that I have replaced the data. If anyone knows better way to do this please let me know. Thank you.
window.parent.document.getElementById("New_"+fnObj.DATA).outerHTML = "<td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>document.getElementById("newCity").value</td>";
window.parent.document.getElementById(dType+"_"+fnObj.DATA).id = 'New_'+fnObj.DATA;
Try this:
var newtr = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
$("#New_"+fnObj.DATA ).replaceWith(newtr);
If you don't want to use jquery you can use something like:
var currentTr = document.getElementById("New_"+fnObj.DATA), parent = currentTr.parentNode,
tempDiv = document.createElement('div');
tempDiv.innerHTML = "<tr id='" + "New_"+fnObj.DATA + "'><td>"+document.getElementById("newBegDt").value+"</td><td>"+document.getElementById("newEndDt").value+"</td><td>" + document.getElementById("newCity").value + "</td></tr>";
var input = tempDiv.childNodes[0];
parent.replaceChild(input, currentTr);
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.