JSON Object into Mustache.js Table - javascript

I'm trying to create a table with a JSON Object using Mustache.js.
I wanted it to show two rows, however it's only showing the second row only.
I suspect that the first row is being overwritten by the second when it's being bound again in the loop.
How do I work my way around it? Or is there a better structure I should follow?
Javascript:
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
Template :
<script id="user-template" type="text/template">
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</script>
table:
<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable">
</tr>
</table>

In additon to your own solution, you should consider using mustache to repeat the row for you:
<script id="user-template" type="text/template">
{{#people}}
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = {people: JSON.parse(text)};
$(document).ready(function() {
var template = $('#user-template').html();
var info = Mustache.render(template, obj);
$('#ModuleUserTable').html(info);
});

I figured out that instead of
$('#ModuleUserTable').html(info);
it should be :
$('#ModuleUserTable').append(info);
Template should be :
<script id="user-template" type="text/template">
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
</script>
and ID should not be on the table row tag. Instead it should be on the table itself:
<table border="1" id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
The moment when it appends, it adds a new row into the table with the JSON data.

Related

Automatically Add rows to the Table when new data comes from a The Websocket with Javascript

I am new to JavaScript, not sure if this very basic question. I am trying to create a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket. The price updates every seconds, I am not sure how should I push the row data into a HTML table dynamically. I tried to iterate the array but still I am not able to proceed.
I have provided the code snippets below as well as external Websocket from where I am pulling the data.
Please let me know how should I insert the row dynamically into a HTML table. Thank you so much in advance.
<body>
<table>
<thead>
<tr>
<th scope="col">Price</th>
</tr>
</thead>
<tbody id="pricetable">
</tbody>
</table>
<script>
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade");
binanceSocket.onmessage = function (event) {
var messageObject = JSON.parse(event.data)
console.log(messageObject.p);
var table = document.getElementById('pricetable')
}
</script>
</body>
Assuming that you have your table in HTML ready with the row for Bitcoin as below. Then just select the <td> cell for price and format the figure accordingly before inserting to it's textContent.
function insertRow(price){
var tr = document.createElement("tr"),
tdCoin = document.createElement("td"),
tdPrice = document.createElement("td"),
docFrag = new DocumentFragment();
tdCoin.textContent = "BTC";
tdPrice.textContent = `${Number(price.slice(0,-6)).toLocaleString("en-US",{style: 'currency', currency: 'USD'})}`;
tr.appendChild(tdCoin);
tr.appendChild(tdPrice);
docFrag.appendChild(tr);
return docFrag;
}
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade"),
table = document.getElementById("pricetable");
binanceSocket.onmessage = function(event) {
var messageObject = JSON.parse(event.data);
table.appendChild(insertRow(messageObject.p));
}
<body>
<table>
<thead>
<tr>
<th>Coin</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody id="pricetable">
</tbody>
</table>
</body>
Add an id to your table, so you can properly access it.
<table id="priceTable">
Then add the new data like so (since i dont know the shape of messageObject.p I am assuming it is a string):
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade");
binanceSocket.onmessage = function (event) {
var messageObject = JSON.parse(event.data);
console.log(messageObject.p);
var table = document.getElementById('priceTable').getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.rows.length);
newRow.innerHtml = `<p>${messageObject.p}</p>`;
}
I have flagged this post as a duplicate of this one. However OP needed a little more help on how to apply the answer to their situation. So I put an answer up

Parsing html with cheerio

I used cheerio for the first time today
This is a simplified version of the html source I want.
<div id="country-table">
<!-- div duplicate cause style -->
<div>
<div>
<table>
<tbody>
<tr>
<td>1</td>
<td>USA</td>
<td>1.6</td>
<td>75.8</td>
<td>132,000</td>
</tr>
<tr>
<td>2</td>
<td>INDIA</td>
<td>12123</td>
<td>1322</td>
<td>123213</td>
</tr>
<tr>
<td>3</td>
<td>BRAZIL</td>
<td>3123</td>
<td>213123</td>
<td>134</td>
</tr>
<tr>
<!-- and more... -->
</tbody>
</table>
</div>
</div>
</div>
and i tried to this:
const axios = require("axios").default;
const cheerio = require("cheerio").default;
axios.get("https://coronaboard.kr").then((html) => {
const arr = [];
const $ = cheerio.load(html.data, { xml: true, xmlMode: true });
const data = $("#country-table>div>div>table>tbody").each((index, item) => {
arr.push(item);
});
console.log(arr);
});
I want to put information in td into tr.
ex){number:x,name:USA,confirmed:x,and more...}
If anyone knows how to do it, please answer me!
If you're wanting to extract the data from the table, then this will help. Follow the comments to help you understand how it works.
var $ = cheerio.load(html.data);
// targets the specific table with a selector
var html_table = $('#country-table>div>div>table');
// gets table cell values; loops through all tr rows
var table_data = html_table.find('tr').map(function() {
// gets the cells value for the row; loops through each cell and returns an array of values
var cells = $(this).find('td').map(function() {return $(this).text().trim();}).toArray();
// returns an array of the cell data collected
return [cells];
}).toArray();
// output table data
console.log('table_data', table_data);

Iterate through selected rows in Datatables

I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.

Pass values from a row to another JSP using jquery

I'm trying to get row values from a bootstrap table to send them to another JSP document while using jQuery, however seems like I can't find a proper way to do that.
<table class="table table-hover">
<thead>
<%
int serial = 0;
int id = 0;
String name = null;
double ammount = 0;
String date = null;
User user = null;
%>
<tr>
<th><%="Serial"%></th>
<th><%="Cost ID"%></th>
<th><%="Cost Name"%></th>
<th><%="Cost Ammount"%></th>
<th><%="Cost Date"%></th>
</tr>
</thead>
<tbody>
<%
try {
int id_id = (int) session.getAttribute("id");
List<Object[]> costs = scm.viewAll(sum.getUser(id_id));
for (Object[] cost : costs) {
id = (int) cost[0];
name = (String) cost[1];
ammount = (double) cost[2];
date = (String) cost[3];
serial += 1;
%>
<tr class="clickable-row" data-href="updatesingle">
<td><%=serial%></td>
<td><%=id%></td>
<td><%=name%></td>
<td><%=ammount%></td>
<td><%=date%></td>
</tr>
<%
}
} catch (Exception e) {
response.sendRedirect("home");
}
%>
This code above is the table code. As you can see the rows are clickable and I'm redirecting to a new page(JSP) when a row clicked, using jQuery:
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.document.location = $(this).data("href");
});
});
What I'm trying to do, is to pass for example the Cost ID(id variable) value to the next JSP page and manipulate it in some way, and the value should be of the specific row I clicked on. Is there a way to do so?
P.S I'm new to jQuery so please be gentle :)
You can save the id in a data- attribute:
<tr class="clickable-row" data-href="updatesingle" data-id="<%=id%>">
And, if you're going to use that ID with JSP, then you can pass it as a parameter to the other page:
window.document.location = $(this).data("href") + "?id=" + $(this).data("id");
But if you're going to get it with jQuery in the other page, you can save the ID into the sessionStorage:
sessionStorage.setItem('clickedUserID', $(this).data("id"));
window.document.location = $(this).data("href");
In the other page, you just get it from the sessionStorage and use it:
var userID = sessionStorage.getItem('clickedUserID');
// do something with the ID
Pro-tip: if you are only printing out a String into your JSP, you can simply just type it into the HTML (and save yourself the extra coding)
Here's my attempt to answer your question:
$(document).ready(function($) {
$(".clickable-row").click(function() {
// you can add the URL for the new page here like:
// var newLocation = "<URL for JSP>?paramName=" + paramValue
// this is just an example of how it would work
var newLocation = window.document.location + "?href=" + $(this).data("href");
alert( newLocation );
// oher values
console.log( $(this).find("td").eq(1).html() ); // 1 for id column, 2 for name, 3 for amount, etc.
window.document.location = newLocation;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<table class="table table-hover">
<tr>
<th>Serial</th>
<th>Cost ID</th>
<th>Cost Name</th>
<th>Cost Amount</th>
<th>Cost Date</th>
</tr>
<tr class="clickable-row" data-href="updatesingle1">
<td>1</td>
<td>id1</td>
<td>name1</td>
<td>amount1</td>
<td>date1</td>
</tr>
<tr class="clickable-row" data-href="updatesingle2">
<td>2</td>
<td>id2</td>
<td>name2</td>
<td>amount2</td>
<td>date2</td>
</tr>
<tr class="clickable-row" data-href="updatesingle3">
<td>3</td>
<td>id3</td>
<td>name3</td>
<td>amount3</td>
<td>date3</td>
</tr>
</table>

Convert HTML table to array [duplicate]

This question already has answers here:
Convert html table to array in javascript
(5 answers)
Closed 7 years ago.
I have a html table
<table>
<tr>
<th>Type</th>
<th>Text</th>
<th>Time</th>
<th>Notification Time</th>
</tr>
<tr>
<td>Lab1</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Monday, Wednessday</td>
</tr>
<tr>
<td>Lab2</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Tuesday, Wednessday</td>
</tr>
</table>
Now I want to use those values of <td> and form an array in php or jquery.
Any idea how to do it in the most simplest way?
In jquery:
var tdCollection = $("table").find("td");
var array = [];
$.each(tdCollection, function(key, el){
array.push($(el).text());
});
console.log(array);
fiddle: http://jsfiddle.net/qqdwct7h/
But it would be better to set an id attribute for the table, beacuse using $(table) isn`t best way to select a certain table.
Check this jQuery traversing and Ajax sample :)
<script type="text/javascript">
var tableRows = $("table tr"),
currentRow,
tableData = [];
for (var i = tableRows.length; i--;) {
currentRow = $(tableRows[i]);
tableData.push({
field1: $(":nth-child(1)", currentRow),
field2: $(":nth-child(2)", currentRow),
field3: $(":nth-child(3)", currentRow),
field4: $(":nth-child(4)", currentRow)
});
}
//Sample Test to verify if data is fetched
console.log(tableData);
$.ajax({
url: "sample-ajax-handler.php",
type: "POST",
data: tableData,
success: function (e) {
//do what you want here :)
}
});
</script>
I wrote a fiddle that allows to generate an array based on the column:
http://jsfiddle.net/5vfm6k6q/2/
Works like this:
var parser = new ArrayParser(),
result = parser.getArray('#table', 'Type'); // table selector, column

Categories

Resources