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;
Related
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>
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
I would like to populate an existing table with json data. I found an example on stackoverflow which does this but with only one column of data. The json data has three sets of data which requires obviously 3 columns. I have experimented with only one row but the jquery code (below) incorrectly displays the table.
<table class="table">
<tr id="row1">
<td = "col1"></td>
<td = "col2"></td>
<td = "col3"></td>
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("#row1").eq(key).find('td').text(value.indx);
$("#row1").eq(key).find('td').text(value.amt);
$("#row1").eq(key).find('td').text(value.jDate);
});
}
OUTPUT IN BROWSER: 167 167 167
It is displaying the last field in all three columns. Any advise on how to do get table to display the correct values would be appreciated.
Your code is updating ALL CELLS with value.indx, then with value.amt and finally with value.jDate... So fast that you only see the final result.
I think what you want to achieve is something more like in this CodePen :
function myFunction() {
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];
$.each(data, function(key, value) {
$("table").find('tr').eq(key).find("td").eq(0).text(value.indx);
$("table").find('tr').eq(key).find("td").eq(1).text(value.amt);
$("table").find('tr').eq(key).find("td").eq(2).text(value.jDate);
});
}
myFunction();
Obviously you have to add rows dynamically into your table, because your data array may contain different amount of objects.
Try this code.
Here we have table which is populated with new rows for each element of data array.
data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
{"indx":2,"amt":3344.4,"vendor":22,"jDate":168},
{"indx":3,"amt":1414.1,"vendor":21,"jDate":169},
{"indx":4,"amt":3441.3,"vendor":31,"jDate":1610}];
$.each(data, function(key, value) {
var tr = $("<tr>");
tr.append($("<td>").text(value.indx));
tr.append($("<td>").text(value.amt));
tr.append($("<td>").text(value.vendor));
tr.append($("<td>").text(value.jDate));
$("#table").append(tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" border="1">
</table>
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.
I have the following html in a website:
<table id="list" class="tablesorter">
<thead id="header">
</thead>
<tbody id="rows">
</tbody>
</table>
I load the header and rows of the table using javascript. Example of how I fill the headers:
$.get( '/getdata',{}, function(mydata) {
// Parses JSON Into Array
var array = $.parseJSON(mydata);
var html = '<tr>';
html+='<th>#</th>';
html+='<th>One</th>';
html+='<th">TOTAL</th>';
var available = {};
for (var i = 0; i < array.length; i++) {
available_item = array[i];
html+='<th><abbr title="'+array[i].text+'"><img src="img/flags2/'+array[i].country+'.png"></img></abbr></th>';
};
html += '</tr>';
$(html).appendTo('#header');
});
The rows are filled in a similar way: ajax get, for loop, and append to html.
Now I need the table columns to be sortable.
I was trying to get it work with jquery tablesorter but it is not working. I suppose that it is not working because my data is loaded using javascript.
How can I make this table sortable?
Add $("#list").tablesorter(); at the end (when table is already filled with all data, thead and tbody)... I am using the same in my application and works fine.
use below code. add $("#list").tablesorter(); at data loop end.
$.get( '/getdata',{}, function(mydata) {
// Parses JSON Into Array
var array = $.parseJSON(mydata);
var html = '<tr>';
html+='<th>#</th>';
html+='<th>One</th>';
html+='<th">TOTAL</th>';
var available = {};
for (var i = 0; i < array.length; i++) {
available_item = array[i];
html+='<th><abbr title="'+array[i].text+'"><img src="img/flags2/'+array[i].country+'.png"></img></abbr></th>';
if(array.length === (i+1)){
html += '</tr>';
$(html).appendTo('#header');
$("#list").tablesorter();
}
};
});
Yes you can do it
Looking at your title making html table sortable (with headers and data loaded using javascript)
It doest matter if you are loading data via jquery or simply using php ...
look for datatables in bootstrap .. This plugin provides all types of data manipulation with the tables that also includes sorting of the data ... you can also perform search in the table. All you have to do is give your table some id like "mytable" then write
$(document).ready( function () {
$('#mytable').DataTable();
} );
after that you can start to include different attributes to select the type of sorting searching etc ... hope that helps