Whing Dela Cruz
asked on
HTML5 Looping table certain Cell
Hi Experts, I have a table named "myTable" with 2 columns, code and Price. I want to display the all price in an alert(). Here's the table;
<Table id="myTable" style="cursor: pointer; >
<tr class="header">
<th style="width:30%;">Code</t h>
<th style="width:200%;">Price< /th>
</tr>
<tr>
<td>amx1</td>
<td>85.00</td>
</tr>
<tr>
<td>pep1</td>
<td>125.00</td>
</tr>
<tr>
<td>pep1</td>
<td>125.00</td>
</tr>
</Table>
<Table id="myTable" style="cursor: pointer; >
<tr class="header">
<th style="width:30%;">Code</t
<th style="width:200%;">Price<
</tr>
<tr>
<td>amx1</td>
<td>85.00</td>
</tr>
<tr>
<td>pep1</td>
<td>125.00</td>
</tr>
<tr>
<td>pep1</td>
<td>125.00</td>
</tr>
</Table>
You meant e.text() rather that e.innerHTML?
You meant e.text() rather that e.innerHTML?No - on a .each() loop the element parameter passed in is an HTML node not a jQuery object. To access the .text() method you would have to wrap the e in a jQuery object like so
$(e).text();
All we want is the text in the cell - so no need to go and incur extra time wrapping the element - just access the contents on the element directly. We could have used textContent insteald of innerHTML - but in this case it does not really make a difference.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
instead the f summing themThe author's intentions are not clear
I want to display the all price in an alert()I made a point of interpreting his request literally and am waiting for feedback.
ASKER
Hi guys, sorry for the late relying of this issue, Julian was exactly answered the context of my question and the second intention is to get the sum of it. How?
Code is the same - just parse the result and add as before
jQuery
jQuery
<script>
$(function() {
var result = 0.0;
$('#myTable tr td:nth-child(2)').each(function(i,e) {
result += parseFloat(e.textContent);
});
alert(result)
});
</script>
JavaScript<script>
var result = 0.0;
var tbl = document.getElementById('myTable');
var td = tbl.querySelectorAll('tr td:nth-child(2)');
for(var i =0; i < td.length; i++) {
result += parseFloat(td[i].textContent);
}
alert(result);
</script>
ASKER
Hi Julian, The code (Javascript) is working, but what about if "var td = tbl.querySelectorAll('tr td:nth-child(2)');" is in form of text within the table child(2). How to change the code? I have changed the td:nth-child(2)') into a text input. Thanks!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
More power to both of you guys, I'm so thankful to God that he gave you such kind of ability to create solutions to solve and help someone out there. More power to both of you, and God bless you, as always!
You are welcome.
Open in new window
Using plain JavaScriptOpen in new window
Working sample here