How to read a list of html tables in JavaScript - 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!

Related

How can I split the following string into an array that I can use to populate a html table

I have a string that looks like:
var str = '{ "abc": {
"decline_reason": "Business rule switched off"
},
"def": {
"decline_reason": "No response by interface"
},
"ghi": {
"decline_reason": "Requested incorrect size" }';
I would like to split that string into an array that I can use to populate a table on a webpage. I intend to use the initial reference ('abc'), with the reason ('Business rule switched off') on row 1, initial reference ('def'), with the reason ('No response by interface') on row 2, etc...
I have tried regex to break it down, and I've managed to find one that removes quotes, but not to break the string down.
I intend to populate the table with code like:
<table id="declinesTable">
<tr>
<th onclick="sortTable(0)">Reference Code</th>
<th>Decline Reason</th>
</tr>
<tr id="lender1">
<td id="lender1"><script>document.getElementById("lender1").innerHTML = declines[0];</script>
</td>
<td id="declineReason1"><script>document.getElementById("declineReason1").innerHTML = declines[2];</script>
</td>
</tr>
</table>
skipping out the value "decline_reason" from the table.
Any suggestions?
Couple of things - your string is missing a final }. Not sure where you're getting the string from, but it's in JSON format, so use JSON.parse to get it into an object, then iterate over the object to do something with each individual nested object. I would strongly recommend using a library like jQuery to help you append it to the table. You can google and very quickly find out how to add jQuery to your project. See below.
function stringParse(str) {
const json = JSON.parse(str);
const html = Object.entries(json).reduce((h, [k, v]) =>
h += `<tr><td>${k}</td><td>${v.decline_reason}</td></tr>`
, "");
$('#declinesTable').append(html);
}
const str = '{ "abc": {"decline_reason": "Business rule switched off"},"def": {"decline_reason": "No response by interface"},"ghi": {"decline_reason": "Requested incorrect size"}}'
stringParse(str);
<table id="declinesTable">
<tr>
<th>Reference Code</th>
<th>Decline Reason</th>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Display array items in one td with each item on a new line

I have an array from a datatable populating a table in my Bootstrap modal.
When displayed in the modal it displays as the below:
This is my current jQuery to populate my table in my modal:
$('#selectedReportDataTable').on('click', 'button[name="deleteContentButton"]', function () {
var deleteRunData = selectedReportDataTable.row($(this).closest('tr')).data();
$('#deleteModal').modal('show');
$('span[name=selectedReport').text(reportSelectedLowerCased);
$('td[name=modalPeriod]').text(deleteRunData.period);
$('td[name=modalSpecParams]').text(deleteRunData.specialParams);
$('td[name=modalFreq]').text(deleteRunData.frequency);
$('td[name=modalTimeFrame]').text(deleteRunData.timeFrame);
$('td[name=modalTime]').text(deleteRunData.time);
$('td[name=modalRecipients]').text(deleteRunData.recipient);
$('#deleteModal').on('shown.bs.modal', function () {
$('#deleteModalNoButton').focus();
});
})
It's the last line:
$('td[name=modalRecipients]').text(deleteRunData.recipient);
that populating the email column
This is the code I have tried:
var abc = deleteRunData.recipient
var def = deleteRunData.recipient.toString().split(", ").join("<br/>");
var ghi = $('td[name=modalRecipients]').text();
var jkl = def.replace(/,/g, "\n")
console.log(abc)
console.log(def)
console.log(ghi)
console.log(jkl)
console.log(abc.join('\r\n'));
and this gives me the following:
If I replace:
$('td[name=modalRecipients]').text(deleteRunData.recipient);
with the following (as an example):
$('td[name=modalRecipients]').text(def.replace(/,/g, "\n"));
It looks like the below:
It's replaced the comma with a space, not what I was after. I want each entry on a new line - what am I doing wrong?
HTML just in case:
<table class="table" style="table-layout: fixed; width: 100%">
<tr>
<th class="modalTable" style="width: 50px">Period</th>
<th class="modalTable" style="width: 85px">Additional details</th>
<th class="modalTable" style="width: 55px">Frequency</th>
<th class="modalTable" style="width: 45px">Time frame</th>
<th class="modalTable" style="width: 25px">Time</th>
<th class="modalTable">Recipient(s)</th>
</tr>
<tr>
<td name="modalPeriod" class="modalTable"></td>
<td name="modalSpecParams" class="modalTable"></td>
<td name="modalFreq" class="modalTable"></td>
<td name="modalTimeFrame" class="modalTable"></td>
<td name="modalTime" class="modalTable"></td>
<td name="modalRecipients" class="modalTable" style="word-wrap: break-word"></td>
</tr>
</table>
God dam it. Soon as i hit submit the answer came instantly using the below code
for (var i = 0; i < deleteRunData.recipient.length; i++) {
$('td[name=modalRecipients]').append('<div>' + deleteRunData.recipient[i] + '</div>');
}
you should replace $('td[name=modalRecipients]').text(def.replace(/,/g, "\n")); with $('td[name=modalRecipients]').html(def.replace(/,/g, "<br \/>")
try this
edit:- rightt well i started this reply before the accepted answer came but i thought i would put it here in-case it other people run into this and need helps.
Original Answer
Totally understand the code blindness, especially with divs and css because this is the most fustrating and angry part of coding the backends! As I understand it, you are looking for multiple emails to display in the email column. So as an example, if there were two recipients, tony#tony.com and crisps#cristony.com, then we would expect
tony#tony.com
crisps#cristony.com
NOTE: NO COMMAS INBETNWNEN THE EMAILS.
When I come across this problem, normally I would write the following code in javascripts
for (var i = 0; i < deleteRunData.recipient.length; i++) {
$('td[name=modalRecipients]').append('<div>' + deleteRunData.recipient[i] +
'</div>');
}
Thsi works some of the time when the deleteRunData exists, if it does not then we have a problem!! Sometimes it does not exist because the people who coded the front ends who we are relying on (server guys), don't make this!! In the case of when deleteRunData does not exist, what I do is create an image of all possible combinations of emails with new lines!!
so for example, for your example i would make a jpeg image of the two emails on photoshops or paintshopro, then i would do
$('td[name=modalRecipients]').append('<img src="http://en.wikipedia.org/wiki/Potato_chip#/media/File:Potato-Chips.jpg" width="500" height="600">')
works for me.
just two extra things that i have come across after regianing my sight
why is tony#test.com receiving five emails about their evening call costs? I would have thought one would suffice?
2.jquery is known to be dangerous when mixed with css and php-sass. please make sure its the rite back end technology for your use case!
hope this helps

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

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);

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>

jquery table selector with condition

i had a table that submitted from my jquery append script, are its possible to find the match value with jquery selectors,
i want to check if the condition >= var $minimumEducation, it will pass to next page when submit, i set the value 0 for High School, 1 for Diploma and so on as it use selectbox, the var $minimumEducation variable come from my php admin, anyone knows how to pass this condition ? thanks
<thead>
<tr>
<th>Name</th>
<th>Relation</th>
<th>DOB</td>
<th>Education</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Uncle</td>
<td>02/19/1955</td>
<td>Bachelor</td>
<td>Carpenter</td>
</tr>
<tr>
<td>Amy</td>
<td>Aunty</td>
<td>02/19/1950</td>
<td>Master</td>
<td>Housewife</td></tr>
<tr>
<td>Eddie</td>
<td>Cousin</td>
<td>02/19/1990</td>
<td>Diploma</td>
<td>Editor</td>
</tr>
</tbody>
</table>
You can select each matched element using the :has selector. To match against minimum education you must build the selector string based on the array mapping the education strings to the $minimumEducation value
$( "tr:has(td[value="bachelor"], td[value="master"])" )
This can be generated similar to the following
var query = "";
for (var i = minimumEducation; i < eduarray.length; i++) {
query += ', td[value="'+eduarray[i]+'"]';
}
query = query.substring(1);
Then just put the query string inside the selector
$( "tr:has("+query+")" )

Categories

Resources