Reading HTML response in Vuejs to display it in a Dialog box - javascript

I am getting a response from the server with the REST request in an HTML format. I have stored this in a data:[] and when I print it on a console it looks like this i.e. HTML. This reply is a String and now my problem is to filter it in JavaScript to make it an array of objects
<table border='1' frame = 'void'>
<tr>
<th>name</th>
<th>age</th>
<th>date of birth</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
<td>10.09.1987</td>
</tr>
</table>
My question is how can I show this HTML data in a dialog box using vuejs.
I want this values as an array of objects like this
[
name,
age,
data of birth,
john,
30,
10.09.1987
]

This is not a Vue.js problem, but an HTML/JavaScript one. You can iterate the cells text content and convert into an array like below.
var stringFromREST = "<table border='1' frame='void'><tr><th>name</th><th>age</th><th>date of birth</th></tr><tr><td>John</td><td>30</td><td>10.09.1987</td></tr></table>";
var tempDiv = document.createElement('div');
tempDiv.innerHTML = stringFromREST;
var cells = tempDiv.querySelectorAll('th,td');
var contentArray = [];
for (var i = 0; i < cells.length; i++) {
contentArray.push(cells[i].innerText);
}
console.log(contentArray);

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

How to Inject HTML using JavaScript

Solution
My question was asked with little knowledge in HTML and JavaScript, I apologize for this. With more experience I can clearly see that this was not a good question asked, anyway the solution to my own question can be found here:
best way to inject html using javascript.
Problem:
I am trying to show the whole list in HTML. For instance, if there are three names, I want the names to be shown in between <td>...</td>. Is there a way I can extract all this list to HTML via JavaScript?
I know I need an array and probably a for loop. Maybe I am thinking too complex.
Here is the HTML code:
<table class = "table table-striped">
<thead>
<tr>
<th>Full Name</th>
</tr>
</thead>
<tbody>
<tr id = "scoreList">
<tr>....</tr>
</tr>
</tbody>
</table>
Here is the JavaScript code:
// Loop through customers
for( var i = 0; i < keys.length; i++){
var k = keys[i];
// var id = customers[k].id;
var name = customers[k].name;
// Add code here to show list of names in html
}
Assuming that you use no frameworks, that's one easy way to do it:
// Generate the <td>'s.
const rendered = keys.map((v) => `<td>${v}</td>`).join('');
// Write them on the screen.
document.getElementById('scoreList').getElementsByTag('tr')[0].innerHTML = rendered;
With pure javascript (and assuming you'll want the <td> elements in <tr> elements) you can use this.
var customers = [
{
firstName: 'John',
lastName: 'Smith'
},
{
firstName: 'William',
lastName: 'Shakespear'
}
]
for(var customer of customers) {
var tdFN = document.createElement('TD');
tdFN.innerHTML = customer.firstName;
var tdLN = document.createElement('TD');
tdLN.innerHTML = customer.lastName;
var tr = document.createElement('TR');
tr.appendChild(tdFN);
tr.appendChild(tdLN);
document.querySelector('table.table.table-striped tbody').appendChild(tr);
}
<table class="table table-striped">
<thead>
<tr>
<th>Full Name</th>
</tr>
</thead>
<tbody>
<tr id="scoreList">
</tr>
</tbody>
</table>

How to read a list of html tables in JavaScript

I have a list of HTML tables given by pandas data frame in the format of:
list_html =
[<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>score</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.776959</td>
<td>grade</td>
<td>grade</td>
</tr>
<tr>
<th>1</th>
<td>0.414527</td>
<td>class</td>
<td>class</td>
</tr>, ... , ... ]
I am trying to visualize this data in an html page and could not do it. I do not have enough experience in web development. My goal is to use JavaScript to loop through each item the list and visualize them below each other in html. It would be great if anybody can help!
This is what I tried so far, its probably completely wrong:
var list_html = list_html // list of html codes as a javascript variable.
var arrayLength = analysis.length;
for (var i in list_html) {
document.getElementById("analysis_1").innerHTML = list_html[i];
}
Given a valid array of strings list_html (actually list_html is not a valid array of strings, since the markup in each entry is not wrapped in quotes) and a container in the DOM with id "analysis_1" it's simply a matter of:
var container = document.getElementById('analysis_1');
for (var i = 0; i < list_html.length; i++) {
container.innerHTML += list_html[i];
}
UPDATE:
well... in your scenario there is no need at all for a loop, you can simply inject a single string by joining the elements in the array:
document.getElementById('analysis_1').innerHTML = list_html.join('');
fast and simple! :)
using jquery's selectors :
Give the 'td' which contains the data a class name, eg: 'MyTd';
Select them all: $(.MyTd).text()
Done!

How to display dynamically added form elements in a table in a different webpage when the data is saved in local storage using purely javascript?

I'm doing a school project in which I'm creating webpages to allow users to input and then display it on another page. I am only using javascript, html and css for the webpages.
On the Create An Event page is a form. I have saved all the input into local storage but now I am unsure on how to retrieve the data to display in on another page called Event History. Here are my codes:
function saveToStorage() {
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
var one={"name":nameofevent,"pos":positions,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
localStorage["CreateEvent"]=JSON.stringify(one);
return false;
}
Whenever the user submits the Create An Event form, the data that the user inputs will be displayed in a table in another page. Here are my codes for the table:
<h1>Events Created</h1>
<table border="1px" id="tab">
<thead>
<tr style=" font-size: 30px">
<th id="event">Name of event</th>
<th>Positions</th>
<th id="">Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>eg. Name</td>
<td>eg. Position1, position2</td>
<td>eg. venue</td>
<td>eg. date</td>
<td>eg. start time</td>
<td>eg. end time</td>
</tr>
</tbody>
var saved=JSON.parse(localStorage.getItem("createEvent"));
alert(saved.name);
//etc
You can simply read from the localStorage in the same way, you wrote to it.
You could add this function to your js:
function loadEvents() {
//get the JSON Object from local storage
var event = JSON.parse(localStorage["CreateEvent"]);
//get the first row in the table
var firstRow = document.querySelector('table tbody tr');
//get the single tds
var eventName = firstRow.querySelector('td:nth-child(1)');
//put the data into the tds
eventName.innerHTML = event.name;
}
Call this function with <body onLoad="loadEvents()"in your View Events page.
Make sure you add the <script /> to the file.
This way it is very cumbersome to select the child nodes, so maybe you would want to put some classes in your markup.

Convert table HTML to JSON

I have this:
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
And I need a JSON format.
{"Name":"Carlos","Age": 22}
I've tried with https://github.com/lightswitch05/table-to-json but it doesn't work for the headings in every row :(
EDIT: http://jsfiddle.net/Crw2C/773/
You can convert the table in the OP to the required format by first converting it to an Object, then using JSON.stringify to get the required string:
<table id="t0">
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<script>
function tableToJSON(table) {
var obj = {};
var row, rows = table.rows;
for (var i=0, iLen=rows.length; i<iLen; i++) {
row = rows[i];
obj[row.cells[0].textContent] = row.cells[1].textContent
}
return JSON.stringify(obj);
}
console.log(tableToJSON(document.getElementById('t0'))); // {"Name:":"Carlos","Age:":"22"}"
</script>
However, that is an ad hoc solution, so will need some work to be adapted to a more general case. It shows the concept though.
Note that there is no guarantee that the object properties will be returned in the same order as they appear in the table, you may get {"Age:":"22","Name:":"Carlos"}.
Assuming all you need is to get the first/second cells of each row as key/value pairs, you can use .reduce() to iterate of the rows and just grab the text content of .cells[0] and .cells[1] to use as each key/value pair:
var t = document.querySelector("table");
var j = [].reduce.call(t.rows, function(res, row) {
res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
return res
}, {});
document.querySelector("pre").textContent = JSON.stringify(j, null, 2);
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<pre></pre>
The Array.prototype.reduce method takes a collection and uses an accumulator to reduce it down to whatever state you want. Here we just reduce it to an object, so we pass one in after the callback.
For every row, we use the first cell's content as the object key, and the second cell's content as the value. We then return the object from the callback so that it's given back to us in the next iteration.
Finally, .reduce() returns the last thing we returned (which of course is the object we started with), and that's your result.
var t = document.querySelector("table");
var j = [].reduce.call(t.rows, function(res, row) {
res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
return res
}, {});
document.querySelector("pre").textContent = JSON.stringify(j);
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<pre></pre>
The Table-to-JSON library that you are using is expecting a different format in your table.
It is expecting a table with all of your headers in the first row, followed by the data in subsequent rows.
In other words, it's expecting your table to be structured like this
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Carlos</td>
<td>22</td>
</tr>
</table>
Here's a forked version of your JSFiddle in which this is working.

Categories

Resources