Javascript XPath table loop td's - javascript

I am trying to create a Chrome Extension that will extract some data from a table. I want to transform the TD's of the TR's in simple lines with each column separated by a pipe | character, ex:
01/01/2020 | XX | 57,43 | |
02/01/2020 | YY | 11,22 | |
Here is a part of it:
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
To iterate over it, I use XPath like this:
function DOMtoString(doc) {
let path_tr = '(//div[#class="contborda"])[4]/table[3]/tbody/tr[position()>1]';
var tr = doc.evaluate(path_tr, doc, null, XPathResult.ANY_TYPE, null);
let alertText = '';
let x = tr.iterateNext();
while (x) {
alertText += x.textContent;
x = tr.iterateNext();
}
return alertText;
}
Here I get the table (ignoring the first TR with column names), but the result is this (just some part of it):
<br> <br> 21/02/2020 <br> Concessionárias<br> <br> 57,43 <br> <br> Visualizar<br> enviar por email <br><br>
I see that XPath is adding BR's on it.
I try to loop over the TD's of these TR's with no success like this:
let path_td = '//td';
var td = tr.evaluate(path_td, tr, null, XPathResult.ANY_TYPE, null);
What is the correct way that I can interact over the TD's and get the raw text of them with no BR's?

Use innerText instead of textContent to avoid line breaks. You can use Document.querySelector() instead of XPath which will make DOM manipulation much easier.
CSS Selectors:
function DOMtoString() {
let lines = [];
let trs = document.querySelectorAll(
'div.contborda > table:nth-of-type(2) > tbody > tr:not(:first-child)'
);
trs.forEach(tr => {
let line = [];
let tds = tr.querySelectorAll('td');
tds.forEach(td => line.push(td.innerText.trim()));
lines.push(line.join('|'));
});
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>
If you have any other reasons you want to stick to using XPath, then you should use dot .// when you want to select nodes relative to nodeContext:
XPath:
function DOMtoString() {
let lines = [];
let path_tr = '//div[#class="contborda"]/table/tbody/tr[position()>1]';
let tr = document.evaluate(path_tr, document, null, XPathResult.ANY_TYPE, null);
let x = tr.iterateNext();
while (x) {
let line = [];
let path_td = './/td';
var td = document.evaluate(path_td, x, null, XPathResult.ANY_TYPE, null);
let y = td.iterateNext();
while (y) {
line.push(y.innerText.trim());
y = td.iterateNext();
}
lines.push(line.join('|'));
x = tr.iterateNext();
}
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>

Related

How do I put randomly generated numbers into a table?

I need to put 6 randomly generated numbers in a an HTML table, I was wondering what would be the best solution, this is my JS code :
function GenerateNumber(){
var sResultat = "";
var iCompteur;
for(iCompteur=0;iCompteur<=6;iCompteur++)
{
sResultat = Math.round(Math.random()* 18) + 1;
}
}
Would calling them with the AddEventListener work? I need to make it appear everytime I load the page, and of course, the numbers need to be different if I reload the page.
Here is my HTML code : (I put numbers temporarily to test my code and to show where I want them to appear)
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class = "FOR">
5
</td>
<td class = "DEX">
4
</td>
<td class= "CON">
4
</td>
<td class ="INT">
4
</td>
<td class="SAG">
4
</td>
<td class="CHA">
3
</td>
</tr>
</table>
</div>
function generateNumber() {
var sResultat
var cells = ["FOR", "DEX", "CON", "INT", "SAG", "CHA"]
cells.forEach(function(cell) {
sResultat = Math.round(Math.random() * 18) + 1;
document.getElementsByClassName(cell)[0].innerText = sResultat
})
}
generateNumber()
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class="FOR">
</td>
<td class="DEX">
</td>
<td class="CON">
</td>
<td class="INT">
</td>
<td class="SAG">
</td>
<td class="CHA">
</td>
</tr>
</table>
</div>
function GenerateNumber(){
var tds = document.querySelectorAll('.table td');
return Array.prototype.forEach.call(tds, function(td){
td.innerHTML = Math.round(Math.random()*18) + 1;
});
}
window.onload = GenerateNumber;
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class = "FOR">
5
</td>
<td class = "DEX">
4
</td>
<td class= "CON">
4
</td>
<td class ="INT">
4
</td>
<td class="SAG">
4
</td>
<td class="CHA">
3
</td>
</tr>
</table>
</div>

Unable to dynamically calculate an input value onchange

I have been trying to get this calculator to work in my WordPress blog but haven't been successful at it.
I did get simple Hello world pop-up to work but not this. I want to calculate the "BPodds". Can you guys tell me what's wrong with this?
function calcStake() {
var BWodds = document.getElementById('BWodds').value;
var div = document.getElementById('div').value;
var BPodds = ((BWodds - 1) / div) + 1;
document.getElementById('BPodds').innerHTML = BPodds;
}
<table class="table" border="0" width="500" cellspacing="1" cellpadding="3">
<tbody>
<tr class="calcheading">
<td colspan="3"><strong>Each Way Lay Calculator</strong>
</td>
</tr>
<tr class="calchead">
<td align="center">Bookmaker Win odds:</td>
<td align="center">Place divider:</td>
<td align="center">Bookmaker Place odds:</td>
</tr>
<tr class="calcrow">
<td align="center">
<input id="BWodds" type="text" value="10" onchange="calcStake()" />
</td>
<td align="center">
<input id="div" type="text" value="4" onchange="calcStake()" />
</td>
<td align="center">
<input id="BPodds" />
</td>
</tr>
</tbody>
</table>
You should use value instead of innerHtml:
document.getElementById('BPodds').value = BPodds;
Here is the fiddle: http://jsfiddle.net/o5ze12mf/
The problem is not with Wordpress,
You are trying to put the result in INPUT with innerHTML but to change the value of INPUT you need to use .value
You code will be like this :
<script type="text/javascript">
function calcStake() {
var BWodds = document.getElementById('BWodds').value;
var div = document.getElementById('div').value;
var BPodds = ((BWodds - 1) / div) + 1;
document.getElementById('BPodds').value = BPodds;
}
</script>
<table class="table" border="0" width="500" cellspacing="1" cellpadding="3">
<tbody>
<tr class="calcheading">
<td colspan="3"><strong>Each Way Lay Calculator</strong></td>
</tr>
<tr class="calchead">
<td align="center">Bookmaker Win odds:</td>
<td align="center">Place divider:</td>
<td align="center">Bookmaker Place odds:</td>
</tr>
<tr class="calcrow">
<td align="center">
<input id="BWodds" type="text" value="10" onchange="calcStake()" />
</td>
<td align="center">
<input id="div" type="text" value="4" onchange="calcStake()" />
</td>
<td align="center">
<input id="BPodds" />
</td>
</tr>
</tbody>
</table>
I just changed
document.getElementById('BPodds').innerHTML = BPodds;
to
document.getElementById('BPodds').value = BPodds;

jQuery problems with parent().remove()

I am trying to clone and remove a table with jQuery, without success.
Here is an example, the table I want to operate:
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2"><img src="./images/add.gif" /><img src="./images/delete.gif" /></td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
Now, the javascript functions add() and remove():
function add(o){
var o = $(o);
var tr = o.parent().parent().parent();
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
}
function remove(o){
var o = $(o);
o.parent().parent().parent().remove();
}
add(this) works perfectly, but the remove(this) is not working, it removes just my "delete.gif" image. What am I doing wrong please?
Look at the jsFiddle.
I used jQuery for what you need.
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2">AddDelete</td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
$(function() {
$(document).on('click', '.adicionar', function(event){
var o = $(event.target);
var tr = o.closest('table');
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
});
$(document).on('click', '.remover', function(event){
var o = $(event.target);
var table = $(o.closest('table'));
table.remove();
});
});
Instead of this parent.parent.parent madness (it's madness, yes it is) why don't you use
element.closest("tr")
to find the row it's in?
This approach will work consistently.

How to show 6 more rows and hide the previous 5 rows of a table using javascript?

I want to only display the first 6 rows of the table and when I press a button, the previous six will be hidden and the next six will be shown.
Here is my javascript that shows the first 6 tables:
function setInnerHTML(){
<%
ArrayList userBoxList = BoxList.getInstance().getUserBoxList();
if(userBoxList.size()>6){%>
document.getElementById('down').disabled = false;
document.getElementById('page').value = counter + 1;
<% size = 6;
}
else{
size = userBoxList.size();
}
for(x=0; x < size; x++)
{
UserBox box = (UserBox) userBoxList.get(x); %>
document.getElementById(origID).onclick = changeColor;
var items = document.getElementById(origID).getElementsByTagName("td");
items[0].innerHTML = "<%=box.getInfo().getBoxNumber()%>";
items[1].innerHTML = "<%=box.getInfo().getBoxName()%>";
items[2].innerHTML = "<%=box.getInfo().getOwnerUserName()%>";
items[3].innerHTML = "<%=box.getInfo().getCurrentSize()%>" + "MB";
origID++;
<%}
%>
}
My HTML code:
<tr style="height:40px;" bgcolor="#FFFFFF" id="0">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
<tr style="height:40px;" bgcolor="#FFFFFF" id="1">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
<tr style="height:40px;" bgcolor="#FFFFFF" id="2">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
<tr style="height:40px;" bgcolor="#FFFFFF" id="3">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
<tr style="height:40px;" bgcolor="#FFFFFF" id="4">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
<tr style="height:40px;" bgcolor="#FFFFFF" id="5">
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
<td align="left"> </td>
</tr>
It's not good practice to mix logic with view. Try to use already existing components to display table.
You could choose displayTag: http://www.displaytag.org/1.2/ or datatables https://datatables.net/ or many others.
Use server side processing with ajax call to display next records.
I solved this problem by creating the table dynamically just using
> document.getElementById.style.display = "table-row" and
> document.getElementById.style.display = "none"
to hide and show the TR.

compare two html tables data line by line and highlight using jquery

I have created a GSP page with two dynamic table with data and now i have to compare the data (inner html) and if any difference then highlight in table 2.
how to do it on clicking button using JS/jquery on clientside?
Table 1 is -
<table class="table loadTable" id ="table1">
<thead>
<tr bgcolor="#f0f0f0">
<td nowrap=""><b>COLUMN_NAME</b></td>
<td nowrap=""><b>DATA_TYPE</b></td>
<td nowrap=""><b>IS_NULLABLE</b></td>
<td nowrap=""><b>CHARACTER_MAXIMUM_LENGTH</b></td>
<td nowrap=""><b>NUMERIC_PRECISION</b></td>
<td nowrap=""><b>COLUMN_KEY</b></td>
</tr>
</thead>
<tbody>
<tr>
<td nowrap="">CountryCode </td>
<td nowrap="">int </td>
<td nowrap="">YES </td>
<td nowrap="">NULL </td>
<td nowrap="">10 </td>
</tr>
<tr>
<td nowrap="">Number </td>
<td nowrap="">varchar </td>
<td nowrap="">NO </td>
<td nowrap="">20 </td>
<td nowrap="">NULL </td>
<td nowrap="">PRI </td>
</tr><tr>
<td nowrap="">Type </td>
<td nowrap="">tinyint </td>
<td nowrap="">NO </td>
<td nowrap="">NULL </td>
<td nowrap="">3 </td>
<td nowrap="">PRI </td>
</tr>
<tr>
<td nowrap="">Date </td>
<td nowrap="">smalldatetime </td>
<td nowrap="">NO </td>
<td nowrap="">NULL </td>
<td nowrap="">NULL </td>
</tr>
</tbody>
table 2 is -
<table class="table loadTable" id ="table2">
<thead>
<tr bgcolor="#f0f0f0">
<td nowrap=""><b>COLUMN_NAME</b></td>
<td nowrap=""><b>DATA_TYPE</b></td>
<td nowrap=""><b>IS_NULLABLE</b></td>
<td nowrap=""><b>CHARACTER_MAXIMUM_LENGTH</b></td>
<td nowrap=""><b>NUMERIC_PRECISION</b></td>
<td nowrap=""><b>COLUMN_KEY</b></td>
</tr>
</thead>
<tbody>
<tr>
<td nowrap="">CountryCode</td>
<td nowrap="">int</td>
<td nowrap="">NO</td>
<td nowrap="">NULL</td>
<td nowrap="">10</td>
<td nowrap=""></td>
</tr>
<tr>
<td nowrap="">PhoneNumber</td>
<td nowrap="">varchar</td>
<td nowrap="">NO</td>
<td nowrap="">20</td>
<td nowrap="">NULL</td>
<td nowrap="">PRI</td>
</tr>
<tr>
<td nowrap="">Type</td>
<td nowrap="">tinyint</td>
<td nowrap="">NO</td>
<td nowrap="">NULL</td>
<td nowrap="">3</td>
<td nowrap="">PRI</td>
</tr>
<tr>
<td nowrap="">EffectiveDate</td>
<td nowrap="">datetime</td>
<td nowrap="">NO</td>
<td nowrap="">NULL</td>
<td nowrap="">NULL</td>
<td nowrap=""></td>
</tr>
</tbody>
</table>
if we click on following button then table 2 should get highlighted with any non matching data with table2.
<div style="align:right"><input type="submit" value="Compare IVR & TNS" /></div>
I wrote a quick function that should work as long as the number of rows is always the same and the user can't remove a row. in which case you should add id's to the rows and compare the rows by id or key.
function compareTables(t1, t2){
var t2rows = t2.find('tbody > tr');
t1.find('tbody > tr').each(function(index){
var t1row = $(this);
var t2row = $(t2rows[index]);
var t2tds = t2row.find('td');
t1row.find('td').each(function(index){
if($(this).text().trim() != $(t2tds[index]).text().trim() ){
console.log('difference: table1:('+$(this).text()+') table2:('+$(t2tds[index]).text()+')');
//set row in error
return;
}
});
});
}

Categories

Resources