1

I have this script that works for now, where I want to add the loan payments together and the total loan values as well but keep the two types separate.

I feel that I'm not using jQuery to its full potential because I'm copying and pasting the same thing twice and repeating my self with code that is similar.

Am I missing something here? Is there a better way to get selected values from multiple input fields?

UPDATE I made a mistake and left the id's the same as the <input /> values. So I updated the code to resemble that.

$(document).ready(function() {
  getTotalAmount();
});

function getTotalAmount() {
  var monthTotal = 0.00;
  var total = 0.00;

  $('input.monthAmt').each(function() {
    monthTotal += parseFloat($(this).val());

    console.log("These is something here: " + monthTotal + " ");
  });

  $('input.loanAmt').each(function() {
    total += parseFloat($(this).val());

    console.log("These is something here: " + total + " ");
  });

  $('#monthAmt').text(monthTotal.toFixed(2).toString());
  $('#loanAmt').text(total.toFixed(2).toString());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Loan 1:
<label>Monthly Amount: </label>
<input class="monthAmt" value="1" />
<label>Loan Amount: </label>
<input class="loanAmt" value="2" />
</br>
</br>
Loan 2:
<label>Loan Amount: </label>
<input class="monthAmt" value="3" />
<label>Loan Amount: </label>
<input class="loanAmt" value="4" />
</br>
</br>
<div id="totalMonthlyAmt">Total Monthly payments: $<span id="moAmt"></span></div>
<div id="totalLoanAmt">Total Loan Amount: $<span id="lnAmt"></span></div>

2 Answers 2

3

I would use javascript for this if I were you, but you can do this with jQuery as well. What you want to do is to put all your repeated code into a function:

$(document).ready(function() {
  
  /* get total amount */
  
  function addAmounts(els) {
    let result = 0;
    els.each((idx, el) => {
      result += parseInt($(el).val())
    })
    return result.toFixed(2)
  }

  $('#monthAmt').text(addAmounts($('input.monthAmt')));
  $('#loanAmt').text(addAmounts($('input.loanAmt')));

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Loan 1:
<label>Monthly Amount: 
    <input class="monthAmt" value="1" />
</label>
<label>Loan Amount: 
    <input class="loanAmt" value="2" />
</label>
<br/>
<br/> Loan 2:
<label>Monthly Amount: 
    <input class="monthAmt" value="3" />
</label>
<label>Loan Amount: 
    <input class="loanAmt" value="4" />
</label>
<br/>
<br/>
<div id="totalMonthlyAmt">Total Monthly payments: $<span id="monthAmt"></span></div>
<div id="totalLoanAmt">Total Loan Amount: $<span id="loanAmt"></span></div>

Update:

With pure javascript, and slightly simplified code:

function addAmounts(selector){
   return [...document.querySelectorAll(selector)].reduce((acc,cur) => acc += parseInt(cur.value), 0).toFixed(2)
}

document.getElementById("totalMonthlyAmt").innerHTML = "Total Monthly payments: " + addAmounts(".monthAmt")
document.getElementById("totalLoanAmt").innerHTML = "Total Loan Amount: " + addAmounts(".loanAmt")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Loan 1:
<label>Monthly Amount: 
    <input class="monthAmt" value="1" />
</label>
<label>Loan Amount: 
    <input class="loanAmt" value="2" />
</label>
<br/>
<br/> Loan 2:
<label>Monthly Amount: 
    <input class="monthAmt" value="3" />
</label>
<label>Loan Amount: 
    <input class="loanAmt" value="4" />
</label>
<br/>
<br/>
<div id="totalMonthlyAmt">Total Monthly payments: </div>
<div id="totalLoanAmt">Total Loan Amount: </div>

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

1 Comment

This is some next lvl stuff!
2

Your code doesn't seem that duplicative to me, given you're looping over two very different kinds of data (monthly vs totals).

This makes what little is duplicated, acceptable.

But if you really want to cut down the code even further, you could do something like:

function getTotalAmount() {
    let totals = {loanAmt: 0, monthAmt: 0};
    $('.monthAmt, .loanAmt').each(function() {
        totals[$(this)[0].className] += parseFloat($(this).val());
    });
    for (type in totals)
        $('#'+type).text(totals[type].toFixed(2).toString());
}

2 Comments

Ok I made a mistake and left the $<span id="loanAmt"></span> the same as the input amount. Is there away to change that in the totals obj to reflect the changes? it should have been something else like $<span id="lAmt"></span>
Sorry, I don't follow. I answered the question as it was asked; please edit the question if there was a problem with it originally.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.