4

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>

1 Answer 1

6

Problem is that you are trying to return from jquery .each() loop. You need to pass the index and get elements instead of using loop 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>

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! That was quick! Thank you so much sir! I think I need to study more about loops! :)
@Randy It is not a problem in normal for loop. But in case of jQuery each, when you return, that means it either breaks loop or continues loop. It wont return value to the outer function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.