JQuery function does not return value

I get the wrong calculation, and the function does not return 3 values ​​from the elements .investment, so that I can calculate them and output them to the elements .payout. 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>
Run code
+4
source share
1 answer

The problem is that you are trying to return from the jquery loop .each(). You need to pass the index and get the elements instead of using a loop.

To break the $ .each loop, you must return false in the loop callback. Returning true proceeds to the next iteration, equivalent to continuing 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>
Run code
+6
source

All Articles