Dynamic table from Firebase using JavaScript for website - javascript

I am creating a table using Google Firebase in JavaScript, but its not showing the table.
Here is my code:
User Table <!--function called on click on tab link-->
<table id="userTableInside" class="w3-table w3-centered w3-striped w3-card-2">
<tr style="background: #cccccc;">
<th>Institute Name</th>
<th>Role id</th>
<th>Institute id</th>
<th>Strikes</th>
<th>Status</th>
<!--<th>Perfomance Rating</th>-->
</tr>
<tr id="mytr">
</tr>
</table>
Added the src script tag above
<script>
//initialized firebase also
function tab1() {
var table= document.getElementById("userTableInside");
var i = 1;
var institudeId = sessionStorage.getItem("InstituteId");
var roleId = sessionStorage.getItem("RoleId");
var ref_1 = firebase.database.ref(institudeId + "/Admin/Usertable/");
ref_1.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var row= table.insertRows(i);
var x= row.insertCell(0);
var x1= row.insertCell(1);
var x2= row.insertCell(2);
x.innerHTML = childData.status;
x1.innerHTML = childData.totalTimeUsed;
x2.innerHTML = childData.report;
i++;
// ...
});
});
</script>

Everything seems fine to me, except the snapshot.forEach. Before using the values in the snapshot, First extract the values from the snapshot using snapshot.val().
Use snapshot.val().forEach. Hope this will solve your problem.
Note:
The listener receives a snapshot that contains the data at the specified location in the database at the time of the event. You can retrieve the data in the snapshot with the val() method.
I didn't check the table insertion logic as i found that snapshot is used directly.

You need to append the data to the table
$("#userTableInside > tbody").append("" + data for col 1 + "" + data for col 2 + "" + data for col 3 + "");
use the proper variable instead of "data for col 1" etc.
make sure you end with a to indicate the end of the table row.
Do this for each time you loop thru your "children" - basically just replace your code in the same place

Related

Displaying array data from session to html table

I've copied data of a html table on page 1 in an array obj(arrData). And i've save that arrData into the session storage. Now on page 2, how do i display the data from the arrData to the html table. New in JS. Thanks in advance
PAGE 1 JS
var arrData=[];
$("#checkout").on('click',function(){
$("#table tr").each(function(){
var currentRow=$(this);
var col1_value=currentRow.find("td:eq(0)").text();
var col2_value=currentRow.find("td:eq(1)").text();
var obj={};
obj.col1=col1_value;
obj.col2=col2_value;
arrData.push(obj);
sessionStorage.myArrData=JSON.stringify(arrData);
});
console.log(arrData);
});
PAGE 2
<table class="table table-checkout" id="table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
PAGE 2 JS
var arrData = JSON.parse(sessionStorage.myArrData);
You need to use sessionStorage.setItem("foo", 12) rather than sessionStorage.foo = 12;
The latter is attaching a new property to the javascript object, not talking to the browser session API. When the page reloads, the object you attached is gone.
To get the item back, use sessionStorage.getItem
Mozilla docs for sessionStorage including setItem and getItem
Once you've done that, you will need a way of creating new table rows in the table. There are a multitude of frameworks for this purpose, but you can also build tables (with a few more steps than with other elements) yourself
How to insert row in HTML table body in Javascript?
As I understand from above, You have data in array of objects after var arrData = JSON.parse(sessionStorage.myArrData);, in below format..
arrData:
[
{col1:"Item1", col2:"quantity1"},
{col1:"Item1", col2:"quantity1"},
...
]
Now to display this data on Page 2
var rows = "";
arrData.map((row)=>{
var row = '<tr><td>'+row.col1+'</td><td>'+row.col2+'</td></tr>';
rows = rows+row;
})
var tbody = document.queryselector('#table tbody');
tbody.innerHTML = rows;

How to store Results using localStorage.setItem and to create a table with 'PlayerName' and 'TotalScore'

I'm currently learning Javascript & HTML and would like some advice.
I've created a very basic quiz using the following Javascript code and I'd like to store the PlayerName and TotalScore in a dynamic table which uses the localStorage functionality available, at the moment I'm simply storing the current PlayerName and TotalScore using the Document.write function in my HTML page, any thoughts, Can anyone help ?
I thought about creating an array called ListOfNames but unsure how to continually add to it the next time the browser opens without declaring the variable as just [ ] again ?
var getUsername = false;
var playerName = "string";
playerName = prompt("Please state your player name");
while( getUsername == false) {
if (confirm("Are you happy with " + playerName + " ?\n Press OK to proceed
OR Cancel to change player name")) {
getUsername = true;
}
else {
playerName = prompt("Please provide a valid player name");
}
};
alert(" Welcome to my Quiz \n\nPlease answer the following questions as
accurately as possible \n\nI will then give you a totalscore at the end");
var totalScore = 0;
var question1 = prompt(" Question 1.\n\nWhich country is José
Mourino from?");
if (question1 == "Portugal" || question1 =="portugal") {
totalScore++;
};
alert("You Scored " +totalScore + " out of a possible 1");
alert("Well done");
var listOfPlayers = [];
listOfPlayers.push(playerName);
localStorage.listOfPlayers = listOfPlayers;
console.log(listOfPlayers);
My HTML is currently set like this which correctly populates the CURRENT playerName and score, I would like to store the ONGOING results and consistently grow the table among friends etc ::
<table class="table">
<thead>
<tr>
<th>Player Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr class="success">
<td><script> document.write(playerName)</script></td>
<td><script> document.write(totalScore)</script></td>
</tr>
<tr class="success">
<td>Liam</td>
<td>11</td>
</tr>
You should not use document.write() as this is an ancient way to include content into a document and leads to JavaScript having to be written in the correct sequence (as you've found out) and can lead to overwriting of the document if you aren't careful.
Instead, you can have the skeleton of a table hard-coded in your page (as you have done), but use the API for a table element to dynamically add rows, cells and cell content to it as needed.
Here's an example:
// Place the following code in a <script> element that comes
// just before the closing body tag (</body>)
// Get references to the table and the button.
var btnAdd = document.getElementById("btnAddRow");
var tbl = document.getElementById("tblOutput");
// Set up a click event handling function for the button
btnAdd.addEventListener("click", function(){
// Set up array for new data. The data can come from anywhere.
// Here, I'm just hard coding it.
var data = ["Scott", "999", "42"];
// Create a new row on the table
var row = tbl.insertRow();
// Loop through the array to insert the data into the cells of the new row
// and to store the data in localStorage
data.forEach(function(value, index){
// Insert a cell in the row at correct index
var newCell = row.insertCell(index);
// Place content from the array in the cell - this can be any data from anywhere
newCell.textContent = value;
});
// Append the array to previously stored data
localStorage.setItem("playerData", localStorage.getItem("playerData") + data.join(","));
});
/* Just some styling for the table */
table, td, th { border:1px solid black; }
td { padding: 3px; }
tr:nth-child(even){
background-color:rgba(255, 255, 0, .3);
}
<table id="tblOutput">
<thead>
<th>Name</th>
<th>ID</th>
<th>Level</th>
</thead>
</table>
<button id="btnAddRow">Add New Row</button>

Assign a Value to a HTML Table Cell using JQuery

There is a table displaying model entries, with each field designated a unique div id combining a keyword and each row's ID. When the user enters a number in the table's input column, a script is supposed to: get the locations of the cells on the same row; and change the values of two predetermined cells based on the values of the other cells.
It seems that tests are successful until the final updating. I've tried using .val(), .value, and .html(), and the resultant cells go blank, or show 0 if the script is error-free. Would someone please post the correct jQuery command and why it works? Many thanks in advance.
The table:
<table id="dt_Positions" class="table table-striped">
<thead>
<tr>
<th class="text-center">Month</th>
<th class="text-center">Owed</th>
<th class="text-center">Bought</th>
<th class="text-center">Total Position</th>
<th class="text-center">Non-Fixed</th>
<th class="text-center">Fixed</th>
<th class="text-center">Fixed Position</th>
<th class="text-center">Proposed</th>
</tr>
</thead>
<tbody>
#if (Model.Forecasts.Any())
{
foreach (var record in Model.Summaries)
{
<tr>
<td id="nmonth#(record.fID)" align="center">#String.Format("{0:d}", #record.Month)</td>
<td id="ntotal#(record.fID)" align="center">#record.NTotal</td>
<td id="nbought#(record.fID)" align="center">#record.NBought</td>
<td id="ntposition#(record.fID)" align="center">#record.NTotalPosition</td>
<td id="nvariable#(record.fID)" align="center">#record.NVariable</td>
<td id="nfixed#(record.fID)" align="center">#record.NFixed</td>
<td id="nfposition#(record.fID)" align="center">#record.NFPosition</td>
<td id="ninput#(record.fID)" align="center"><input class="nInput" type="number" name="quantity" min="1" max="50000"></td>
</tr>
}
}
</tbody>
</table>
The script:
#section Scripts
{
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('[id^=ninput]').keyup(function (e) {
var $id = $(this).attr('id');
var $i = $(this);
var $idNum = $id.slice(6);
var $tp = $('#ntposition' + $idNum);
var $fp = $('#nfposition' + $idNum);
var $nt = $('#ntotal' + $idNum);
var $nh = $('#nbought' + $idNum);
var $f = $('#nfixed' + $idNum);
//The lines below appear to be the hiccup
$tp.val($nh.val() + $i.html() - $nt.val());
$fp.val($nh.val() + $i.html() - $f.val());
debugger;
});
});
</script>
}
EDIT: Examples of ids returning "NaN" are:
ntotal = 29, nbought = 5, ntposition = -24, nvariable = 3, nfixed = 26, nfposition = -21, with all appearing to be int from testing the View, but ntotal, nbought, and nfixed showing "NaN" in the console.log and resulting in "NaN" appearing in the test View after an ninput = 5.
$i is the textbox, so to get its value you need to use $i.val(). The other elements are table cells, so to get or set the values you need .text(), not .val(). However you over complicating code by using id attributes. Instead, remove then and use relative selectors
$('input').keyup(function() { // or $('.nInput').keyup
var i = Number$(this).val());
var cells = $(this).closest('tr').children('td');
var tp = cells.eq(3);
var fp = cells.eq(6);
// Get current cell values as a number
var nt = Number(cells.eq(1).text());
var nh = Number(cells.eq(2).text());
var f = Number(cells.eq(5).text());
// Update totals
tp.text(nh + i - nt);
fp.text(nh + i - f);
});
Side note: The value of var i = $(this).val(); could be null but not sure how you want to handle this - possibly just use
var i = $(this).val();
if (!i) {
return; // don't do any calculations
}
You need to know the difference between val(), text() and html()
val() is for getting and setting values for form elements, input, select etc.
text() is for getting and setting plain unformatted text for non form elements.
html() is for getting and setting inner Html from a node
So what you want is:
$tp.text($nh.text() + $i.val() - $nt.text());
$fp.text($nh.text() + $i.val() - $f.text());
Also be careful as + is both mathematical addition and string concatenation in javascript so you may want to cast your parse the strings to the appropriate number type.

Accessing <td> in HTML Table Using JavaScript

I am trying to attach a row to an editable table using data from an array. In order to do this, I'm adding a row, then utilizing a save feature in order to manipulate the s of the row. My HTML table is:
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody></tbody>
</table>
Being that the array data will be entered into the most recently added row, I've just accessed that using the code below, however now I am struggling to access the actual cells. My current code is:
function UpSave(rowData) {
var tblData = document.getElementById("tblData");
var lastRow = tblData.rows[tblData.rows.length - 1 ];
var tdDate = lastRow.children("td:nth-child(1)");
var tdTime = lastRow.children("td:nth-child(2)");
var tdTreatmentNum = lastRow.children("td:nth-child(3)");
var tdCellNum = lastRow.children("td:nth-child(4)");
console.log(par);
var tdWasteContNum = lastRow.children("td:nth-child(5)");
var tdButtons = lastRow.children("td:nth-child(6)");
tdDate.html(tdDate.children(data[rowData][0]));
tdTime.html(tdTime.children(data[rowData][1]));
tdTreatmentNum.html(tdTreatmentNum.children(data[rowData][2]));
tdCellNum.html(tdCellNum.children(data[rowData][3]));
tdWasteContNum.html(tdWasteContNum.children(data[rowData][4]));
tdButtons.html("<img src='trash.png' class='btnDelete'><img src='pencil.png' class='btnEdit'><img src='up.png' class='btnUp'><img src='down.png' class='btnDown'>");
};
but the .children at the end of the variables are not valid. Any ideas on what to have instead in order to access those cells in the row?
(data is the array containing the text I'm putting into the )
It looks like you never clearly defined the variable tblData by leaving out quotations when you do your original getElementById. Add this to Replace the first line in the function:
var tblData = document.getElementById("tblData");
Adding the quotations will bind the table in the DOM to the variable, then you can do the rest of the stuff.
Revised answer using jQuery:
var $tblData = $("#tblData");
var $lastRow = $tblData.find('tr').last();
var $tdDate = $lastRow.find('td').eq(1);
var $tdTime = $lastRow.find('td').eq(2);
var $tdTreatmentNum = $lastRow.find('td').eq(3);
var $tdCellNum = $lastRow.find('td').eq(4);
//console.log(par);
var $tdWasteContNum = $lastRow.find('td').eq(5);
var $tdButtons = $lastRow.find('td').eq(6);
$tdDate.html(data[rowData][0]);
$tdTime.html(data[rowData][1]);
$tdTreatmentNum.html(data[rowData][2]);
$tdCellNum.html(data[rowData][3]);
$tdWasteContNum.html(data[rowData][4]);
$tdButtons.html("<img src='trash.png' class='btnDelete'/><img src='pencil.png' class='btnEdit'/><img src='up.png' class='btnUp'/><img src='down.png' class='btnDown'/>");
But, if you still want to use pure javascript, try changing the
.children("td:nth-child(x)");
to
.childNodes[x];
Edit note: I changed the inside of the .html(...) function calls so just use the array directly. Previously I had just copy/pasted the OP code for that portion.

Handling the table from a html form with javascript

<table id="production">
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
</table>
Product Name:
Product Quanitity:
Add
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table = document.getElementById("production");
var rows = table.rows;
var cell1 = rows[0].insertCell(-1);
var cell2 = rows[1].insertCell(-1);
cell1.innerHTML = prdn;
cell2.innerHTML = prdq;
}
I need someone help me understand how I can insert data in separate column in database; suppose I have a table of three rows and three columns, columns are created by using td tags, now in the first and last columns elements are predefined and so any data should insert in the second column of the table after clicking the button. because the code above is inserting the data in raw cells by default.
i am adding the fiddle here
http://jsfiddle.net/3e7rh/2/
As you can see here, you need to add in the last - 1 column.
http://jsfiddle.net/3e7rh/8/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].insertCell(rows[0].cells.length - 1);
var cell2=rows[1].insertCell(rows[1].cells.length - 1);
cell1.innerHTML=prdn;
cell2.innerHTML=prdq;
}
Update:
http://jsfiddle.net/3e7rh/10/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].cells[1].textContent=prdn;
var cell2=rows[1].cells[1].textContent=prdq;
}
Get the table. Iterate over all rows and fill in the first td (Because you are using th as the first one)
var table = document.getElementById("production")
rows = table.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++)
{
columns = rows[i].getElementsByTagName("td");
columns[0].textContent="text"; //First Td second column in your case
}
Jsfiddle:http://jsfiddle.net/7xs6v/1/
I am assuming you want to fill the same text in every first td(second column). If you want individual then you can use the index specificallyinstead of iterating over for loop

Categories