whisk
whisk

Reputation: 655

Getting multiple values from inputs and adding them based on their class name

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>

Upvotes: 1

Views: 63

Answers (2)

symlink
symlink

Reputation: 12209

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>

Upvotes: 3

Mitya
Mitya

Reputation: 34556

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());
}

Upvotes: 2

Related Questions