Alexandre Bourlier Alexandre Bourlier - 3 years ago 69
jQuery Question

.each() not iterating properly

I have been struggling with this issue for a few hours now without understanding the behaviour I have got. I did not found this issue on any other post (although I have found many related to the

.each()
method).

Anyway here I am:

This is the HTML I what to iterate upon:

<input type="text" id="investment" /><br />
<table id="fundTable">
<tr>
<td class="rentability"> <span class="someClass"> 0.12 </span> </td>
<td class="absoluteResult"></td>
</tr>
<tr>
<td class="rentability"> <span class="someClass"> 0.24 </span> </td>
<td class="absoluteResult"></td>
</tr>
<tr>
...
</table>


The idea is: the user will enter a value in the textField
#investment
.
onChange
, JQuery will populate the
.absoluteResult
table column by multiplying the user input by the
.rentability
value.

Here is the JQuery part then:

$('#investment').change(function() {
var investment = $('#investment').val(),
currentlyDisplayedRentability,
updatedAbsoluteResult

$('#fundTable tr').each(function(index, tableRow) {
currentlyDisplayedRentability = $(tableRow + "span").html()
currentlyDisplayedRentability = parseFloat(currentlyDisplayedRentability)
updatedAbsoluteResult = currentlyDisplayedRentability * investment
$(tableRow + "td[class=absoluteResult]").html(updatedAbsoluteResult)
})
})


What happens is that all
.absoluteResult
rows are populated using the value of the first row of the
.rentability
column.
Only one value is used for all the pultiplication. It is as if
.each()
is iterating correctly on one column (
.absoluteResult
) and not on the other (
.rentability
).

I do not understand why.

Answer Source

Try this:

$('#investment').change(function() {
        var investment = parseFloat($('#investment').val());

        $('table tr').each(function() {
            var $tr = $(this);
            var rentability = parseFloat($tr.find('.someClass').text());

            $tr.find('.absoluteResult').html(investment * rentability);
        })
    })

code: http://jsfiddle.net/qYSAH/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download