Selector and Iterating Through a Table Within a Div - javascript

I have been working on this and cannot get this iterator to work. I have the following HTML and am trying to iterate through all rows (except the first row) and extract the values in cells (td) 2 and 3 :
<div id="statsId">
<table width="220" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="65"/>
<td width="90"/>
<td width="65"/>
</tr>
<tr style="font-weight: bold;">
<td align="left">$1.00</td>
<td>
UserID1
</td>
<td>Single</td>
</tr>
<tr>
<td align="left">$6.99</td>
<td>
UserID2
</td>
<td>Multiple</td>
</tr>
<tr>...
.....(snip)
I tried the following iterator to iterate through all except the first row of the table that is a child of "div#statsID" and get the values of the 2nd and 3rd cells (in the example, the first extracted cells would have values of "UserID1" and "Single"), but it doesn't work.
$('div#statsId > table tr:not(:nth-child(1))').each(function(i, ele) {
var secondCol = $('td:nth-child(2)', ele).innerHTML
var thirdCol= $('td:nth-child(3)', ele).text()
.....
});
Any suggestions on how to specify and iterate through the rows (except the first) of a table that is a child of a div would be appreciated.

$("#statsId > table tbody tr:not(:first)").each ( function() {
var secondCol = $(this).find('td:nth-child(2)').html();
var thirdCol= $(this).find('td:nth-child(3)').text();
});
Note
You can use the id selector independently. No need to use the tag name.
There is no innerHTML for a jQuery object. Use html() instead

Related

How to change text in table column using javascript

I have this code in my website is there any way to change text inside (td) tag in table using javascript
<div id="mvctable">
<table width="100%">
<tbody>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcvisit.png"> Visit Today : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcmonth.png"> This Month : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvctotal.png"> Total Visit : 1
</td>
</tr>
</tbody>
</table>
</div>
You need to find the td node you want to change via javascript. The most direct is to add an unique id attribute to the td you want to edit. Then use .textContent to set it.
document.getElementById("uniqueIdHere").textContent="newtext";
If you can't add unique ids then you will need to find via a known position or via the existing text in the td tag.
firstTD = document.getElementById("mvctable").querySelector('td');
firstTD.textContent="newtext";
You could get all of the TDs and loop through
tdElements = document.getElementById("mvctable").getElementsByTag('td');
for(var i = 0; i < tdElements.length; i++){
//do something to each td like
tdElements[i].textContent = "something new...";
}
Need more info to give you more details.

How do I filter a table by any matching code/name and not every available field

I'm trying to do the following: I have a table populated with data from the DB. Apart from that, I have an input where you can write something and a button that will filter, only showing the lines that have that string. This is working now!
The thing is, the input should only allow you to filter by foo.name/foo.code (two propertys of my entity).
I'm adding the code I have in case anyone can guide me out, I've tried several things but this are my first experiences with JQuery while I have a strict story-delivery time. Thanks everyone!
<tbody>
<c:forEach var="foo" items="${foo}">
<tr id = "fooInformation" class="mtrow">
<th id="fooName" scope="row">${foo.name}</th>
<td id="fooCode" class="left-align-text">${foo.code}</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</c:forEach>
</tbody>
$("#search").click(function () { -> button id
var value = $("#fooRegionSearch").val(); -> value of the input
var rows = $("#fooRegionTable").find("tr"); -> table id
rows.hide();
rows.filter(":contains('" + value + "')").show();
});
To start with, your HTML is invalid - there cannot be elemenets with duplicate IDs in HTML. Use classes instead of IDs.
Then, you need to identify which TRs pass the test. .filter can accept a callback, so pass it a function which, given a TR, selects its fooName and fooCode children which contain the value using the :contains jQuery selector:
$("#search").click(function() {
var value = $("#fooRegionSearch").val();
var rows = $("#fooRegionTable").find("tr");
rows.hide();
rows.filter(
(_, row) => $(row).find('.fooName, .fooCode').filter(`:contains('${value}')`).length
).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fooRegionTable">
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name1</th>
<td class="fooCode" class="left-align-text">code1</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name2</th>
<td class="fooCode" class="left-align-text">code2</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</table>
<button id="search">click</button><input id="fooRegionSearch" />

how to search for a checkbox inside innerHTML?

I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined
but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.
The code you are looking for is this
$(':checked')
you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.
I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).
$(".beru").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.celkem').each(function(){
// for each celkem, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
td {
width: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"</td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"</td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
If you already have a reference to the DOM element then just select all the checkboxes using a selector.
var cbList = cell.querySelectorAll("[type='checkbox']");
for(var i = 0; i < cbList.length; i++){
//do something with each checkbox
//cbList[i];
}
Remember a node list is not an array, so you can't use forEach ;)

Selecting td element in a tr

Here is the code I want to process using javascript / jquery
EDITED THE BELOW CODE BLOCK FOLLOWING THE COMMENTS
<table>
<tbody>
<tr class="promote">
<td>1</td>
<td><span class="team_logo visible-lg visible-sm" style=""></span><a class="team_name " href="/team/show/7473/Power-Hiters">Power Hiters</a><span class="online" title="user is online"></span></td>
<td style="text-align:center">5</td>
<td style="text-align:center">10</td>
<td style="text-align:center">5</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">6.713</td>
</tr>
<tr> <!-- Similar Above tr Content --> </tr>
<tr> <!-- Similar Above tr Content --> </tr>
<tr> <!-- Similar Above tr Content --> </tr>
</tbody>
</table>
I want to get the inner content/html of each <td> tag in a array using javascript / jquery
Extra Info:
When I tried it seems jquery strips the td and tr tags.
Actual thing I want to do is extract td in a multi dimensional array for each tr
the table structure:
<table>
<tbody>
<tr> <!-- Above tr Content --> </tr>
<tr> <!-- Above tr Content --> </tr>
<tr> <!-- Above tr Content --> </tr>
</tbody>
</table>
Since you want a multidimensional array, you will need to:
Make an array that will hold all table data
Iterate through all tr and create an array per row
Push that array in the first one, that holds all table data.
something like this:
var tableContent = [];
$('table tr').each(function(){
var trcontent = [];
$('td', this).each(function(){ trcontent.push($(this).text()); });
tableContent.push(trcontent);
})
console.log(tableContent);
example in jsfiddle
Try,
var arr = $("#cache").find('td').map(function(){ return this.textContent; }).get();

Testing the RemoveNode DOM function

I have the following test html:
<table width="80%" border="0" cellspacing="0" cellpadding="1" >
<tr>
<td class="tableBorder">
<table id="scriptsT" name="scriptsT" width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td colspan="4" class="tableTitle">› College Foo - ScriptList:</td>
</tr>
<tr class="rowHeaders">
<td width="4%">ScriptName</td>
<td width="2%">Main Script (Radio)</td>
<td width="2%">(Ext)</td>
<td width="2%">Del Script</td>
</tr>
<tr id="foo[1]" name="foo[1]" class="rowHeaders">
<td id="sTD" name="sTD" width="4%">Script1</td>
<td width="2%">
<input type="radio" name="main" id="main" value="">
</td>
<td id="tTD" name="tTD" width="2%">Php</td>
<td width="2%"><input type="Button" class="textbox" name="SelScript" id="" value="DelScript" onClick="javascript: DelScript(1); return false;"></td>
</tr>
</table>
</td>
</tr>
</table>
=======================================================
I'm trying to remove the node, using the "DelScript function, that tries to use an ID to select the given TR, based on each TR having a unique ID, in this case foo[1], etc..
In my test DelScript, I 1st get the table, and then try to get the childnode (the "TR") to delete.
//--handle/simulate the deletion of the tr in the scriptTBL for the id
function DelScript(id)
{
var scriptTBL=document.getElementById("scriptsT");
var a="foo["+id+"]"
var test=document.getElementById("foo[1]");
//scriptTBL.parentNode.removeChild(test);
scriptTBL.removeChild(test);
alert("foo");
var a;
}
However, I'm screwing something up, as I'm not able to delete the node.
I'm running FF4, and firefox seems to be saying the node can't be found (???).
I've also tried using the parentNode a well but get the same results.
Thank you for any pointers.
If you just want to
"delete the TR where the clicked 'delete' button is located"
You don't need any of those id attributes.
<input type="Button" onclick="DelScript(this);return false;">
function DelScript(theClickedButton) {
var tr = theClickedButton.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}
The table rows are not children of the <table>, they're children of the <tbody> element inside it. Even if there's not a <tbody> in your markup, there's one in the DOM. You could go up the DOM from the child element itself, or you could find the <tbody>
var tbody = document.getElementById('scriptsT').getElementsByTagName('tbody')[0];
FF is likely inserting a <tbody> element in between your <table> and <tr>, as the HTML specification demands. You don't even need to know the table ID. The attempt you commented out was almost right, but you need test.parentNode instead of table.parentNode - you want to get the row's parent node, not the table's:
function deleteRow(n){
var el = document.getElementById('foo['+n+']');
return el.parentNode.removeChild( el );
}
The TR is not a child of the TABLE. It is a child of the TBODY that is implicitly a child of the TABLE. Try this:
scriptTBL.children[0].removeChild(test);
Also, install FireBug so that you can browse the DOM tree and set breakpoints in your scripts to examine what they are doing to the dynamically rendered HTML.

Categories

Resources