Randy Randy - 7 months ago 8
Javascript Question

jQuery function doesn't return values

I'm getting the wrong calculation and the function doesn't return the 3 values from

.investment
elements so that I'll be able to calculate them and output them into
.payout
elements. What am I doing wrong here?



function investmentArray() {
$('.investment').each(function() {
var text = $(this).text().slice(0, -2);
text = parseFloat(text.replace(/,/g, ''));
text = Number(text);
return text;
});
};

function payoutCalc() {
var i = investmentArray();
return i * 1.8;
}

var payoutArray = function() {
var el = $('.payout');
el.each(function() {
var result = Number(payoutCalc()).toFixed(2);
$(this).html(result + " $");
});
}
payoutArray();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<th>Investment</th>
<th>Payout</th>
</tr>
<tr>
<td class="investment">1,937.00 $</td>
<td class="investment">285.00 $</td>
<td class="investment">1,926.00 $</td>
</tr>
<tr>
<td class="payout"></td>
<td class="payout"></td>
<td class="payout"></td>
</tr>
</table>




Answer

Problem is that you are trying to return from loop. You need to pass the index and get elements using that.

To break a $.each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

function investmentArray(c) {
  text = $('.investment').eq(c).text().slice(0, -2);
  text = parseFloat(text.replace(/,/g, ''));
  text = Number(text);
  return text;
};

function payoutCalc(c) {
  var i = investmentArray(c);
  return i * 1.8;
}

var payoutArray = function() {
  var el = $('.payout');
  el.each(function(i, val) {
    var result = Number(payoutCalc(i)).toFixed(2);
    $(this).html(result + " $");
  });
}
payoutArray();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Investment</th>
    <th>Payout</th>
  </tr>
  <tr>
    <td class="investment">1,937.00 $</td>
    <td class="investment">285.00 $</td>
    <td class="investment">1,926.00 $</td>
  </tr>
  <tr>
    <td class="payout"></td>
    <td class="payout"></td>
    <td class="payout"></td>
  </tr>
</table>

Comments