Reading text in columns from HTML tables - javascript

I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:
<table id="country_LE_table" style = "display:none">
<tr>
<td>Japan</td>
<td>83.7</td>
</tr>
<tr>
<td>Switzerland</td>
<td>83.4</td>
</tr>
</table>
My Javascript is:
<script type="text/javascript">
function getLifeExpectancy() {
var Country = "<?php echo $Country ?>";
document.write(Country); // this gets read OK
var table = document.getElementById("country_LE_table");
var tr = table.getElementsByTagName("tr");
document.write(tr.length); document.write("<br>"); // works as expected
for (var i = 0; i < tr.length; i++) {
document.write(tr[i].innerHTML); document.write("<br>"); // works well up to here
// the following doesn't work
var td = tr[i].getElementsByTagName("td")[0];
if (td = Country) { //need td.fullHTML/value/fullText?
return tr[i].getElementsByTagName("td")[1]; // return the number
}
document.getElementById("demo").innerHTML = getLifeExpectancy();
</script>
If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.

Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
{
}

Related

Use javascript function in th:if for filtering some table entities

I want to hide the table rows that do not satisfy a date condition written in javascript function.
the th:onclick attribute is working fine and returns me the correct comparison. But when I run the same in th:if the function is not called!
the syntax for the function call:
case 1: the function is called and returns me the true or false
<tr th:each="patient : ${patients}" th:onclick="compareDates([[${patient.dateConverter()}]])">
case 2 that I want to use for the table row filtering: the function is not called:
<tr th:each="patient : ${patients}" th:if="compareDates([[${patient.dateConverter()}]])">
the js function is as follows:
<script th:inline="javascript">
/*<![CDATA[*/
function compareDates(date) {
var date1= document.getElementById("appDate").valueAsDate.toLocaleDateString();
return date == date1;
}
/*]]>*/
</script>
I tried to use th:hidden attribute as well I am getting the following error:
Caused by: org.attoparser.ParseException: Could not parse as expression: "compareDates([[${patient.dateConverter()}]])" (template: "index" - line 277, col 50)
at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
... 121 more
For those having the same challenge, I implemented the table filtering by pure javascript after thymeleaf generated the table. The js function is as follows:
function compareDates() {
var rows = document.getElementsByTagName("table")[0].rows;
for (let i = 1; i < rows.length; i++) {
var td = rows[i].getElementsByTagName("td")[2];
var split= td.innerHTML.split(" ");
if(split[0]!= document.getElementById("appDate").valueAsDate.toLocaleDateString()){
rows[i].style.display = "none";
}
else {
rows[i].style.display = "table-row";
}
}
}
references:
Hiding a <td> depending on the Condition
how to get a td value of a table using javascript

How to create an array from the columns of a table in Javascript?

I have an HTML table like this:
SALES RENTS
ROME MILAN ROME MILAN MONEY
The HTML code is the following:
<TR>
<TD CLASS=HD1 COLSPAN=2>SALES</TD>
<TD CLASS=HD1 COLSPAN=2>RENTS</TD>
<TD CLASS=HDCOLSEP> </TD>
</TR>
<TR>
<TD>ROME</TD>
<TD>MILAN</TD>
<TD>ROME</TD>
<TD>MILAN</TD>
<TD>MONEY</TD>
</TR>
What I need, is to create with javascript an array like this:
(ROME-SALES, MILAN-SALES, ROME-RENTS, MILAN-RENTS, MONEY).
I have already created the array that contains the element of the first row.
Below you can find my code as it was in the past (At the beginning I needed just to take the elements of the first TR). Now I need to modify it and to create an array as specified before.
I don't know if it is clear from the table, but the first ROME and MILAN columns are referred to the column SALES, the second ROME and MILAN are referred to the RENTS column, while MONEY doesn't have any dependence.
Do you have any idea to do this?
Thanks in advance.
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
var header_vals = [];
header_fields.each(function(idx, val) {
var $$ = $(val);
header_vals.push($$.text());
});
return header_vals;
}
It is definitely possible to read values from the table cells. I edited the post a bit to illustrate the code.
I presume that HTML structure is rigid and you always have two rows of titles in the thead and somewhat random number of merged cells in the first row.
You’d want to match the number of columns in both rows, i.e. take the colspan number into account when traversing the cells.
Read both rows and generate strings by combining cell values in corresponding columns.
For example:
function readTableRow(row) {
var values = [];
$("td", row).each(function(index, field) {
var span = $(field).attr("colspan");
var val = $(field).text();
if (span && span > 1) {
for (var i = 0; i<span; i++ ) {
values.push(val);
}
} else {
values.push(val);
}
});
return values;
}
function getColumnsVal(id) {
// Read the first row, taking colspans into account
var first_row = $("table#" + id + " thead tr:eq(0)");
var first_row_vals = readTableRow(first_row);
// Read the second row, taking colspans into account
var second_row = $("table#" + id + " thead tr:eq(1)");
var second_row_vals = readTableRow(second_row);
if (first_row_vals.length != second_row_vals.length) {
return null;
}
var results = [];
for (var i = 0; i<first_row_vals.length; i++) {
results.push([first_row_vals[i].trim(), second_row_vals[i].trim()].filter(function (el) {return el}).join("-"));
}
return results;
}
function displayResults(results) {
var result = "RESULT: <br />";
results.forEach(function(r) {
result = result + r + "<br />";
});
$("#result").html(result);
}
displayResults(getColumnsVal("sample"));
JSFiddle:
https://jsfiddle.net/adanchenkov/n61dqfrs/

How to show table rows based on URL parameter

Currently the page is accessed using a link, for instance help.html?show=charInPw.
The table is written in the following manner:
<table>
...
<tbody class="table-body">
<tr class="pwLen"><td colspan="5" class="subheading">Password Length</td></tr>
<tr class="pwLen"><td class="first">Minimum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="pwLen"><td class="first">Maximum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td colspan="5" class="subheading">Characters in Password</td></tr>
<tr class="charInPw"><td class="first">Minimum numeric characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td class="first">Minimum alphabetic characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
...
The CSS is as follows:
table tbody tr{
text-align: center;
display: none;
}
(There are also trs in thead and they are always shown by default.)
Then I have some Javascript code as follows (jQuery is not an option):
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
for (i = 0; i < document.getElementsByClassName(c); i++)
document.getElementsByClassName(c)[i].style.display='table-row';
</script>
However I am not able to get my rows to show.
How should I change the code on the page to show only the rows referenced by the show parameter?
Edit #1: As a test I did the following hard-coding but it didn't work too!
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
var trs = document.getElementsByClassName('pwLen');
for (i = 0; i < trs.length; i++)
trs[i].style.display='table-row';
</script>
Edit #2: I have combined two solutions below into one - please see https://jsfiddle.net/tea45p2o/. The demo output shown is what I want, however I am not able to see that when I save the file and open the page in my browser. What is going on?
With much help from BJohn and MrJ, I have come up with my solution as follows:
<script>
function show() {
var url = new URL(window.location.href);
var c = '.' + url.searchParams.get("show");
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
}
</script>
Then, I changed my <body> to
<body onLoad="show();">
Use below code:
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
You also need to append dot (.) with class name, which you are getting from the URL.
Please find the fiddle here
ŷou are missing to place .length
for (i = 0; i < document.getElementsByClassName(c).length; i++)
But I think it would be more readable on this way
for(let TR_x of [... document.getElementsByClassName(c) ]) {
TR_x.style.display='table-row';
}
but I definitely prefer
document.querySelectorAll('.'+c).forEach(trX=>{ trX.style.display='table-row' })

how do i write to an html from a javascript function?

i have a problem with my javascript and html
i was trying to write a html element using a function from my javascript
here's my code
function write();
{
for(var i=0;i<arr.length;i++)
{
document.write("<td>"+arr[i]+"</td><br>")
}
}
and code at my index.html, i want put that write inside my table row
<tr>
<script>write();</script>
</tr>
i have attached my javscript to my html document, but nothing happened
can u guys help me to put make that function work??
thanks guys!!
As per your question description, for writing html or dom elements say, you need to first create element(until you already have in which case you can use document.getElementById()) and then add text.
For creating:
# Create new dom element
var td = document.createElement("td");
Adding text:
td.appendChild(document.createTextNode('hiii'))
In your case:
function write(){
var element;
for(var i=0;i<arr.length;i++) {
element = document.createElement("td");
element.appendChild(document.createTextNode(arr[i]));
}
}
Give your row an id like this:
<tr id="myRow">
</tr>
Also i would recommend you to implement the function call in your javascript file.
Try something like this:
window.onload = function(){
write();
};
function write(){
for(var i = 0; i < arr.length; i++){
document.getElementById("myRow").innerHTML += "<td>" + arr[i] + "</td><br>";
}
}
you can check html below:
<table>
<tr id="myid" >
</tr>
</table>
and javascript would be like this
var row = document.getElementById("myid");
var x = row.insertCell(0);
x.innerHTML="New cell";
HTML:
<table>
<tr id='row'></tr>
</table>
JS:
function write(arr) {
var row = '';
for (var i = 0; i < arr.length; i++) {
row += '<td>'+arr[i]+'</td>'
}
document.getElementById('row').innerHTML = row;
}
write(['a', 'b', 'c', 'd']);
working demo: http://jsfiddle.net/uhaEL/

question regarding javascript;Html generation and search current webpage for tags

Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.

Categories