Add values of fields in jQuery

Asked

Viewed 51 times

-1

I have the following HTML

<legend>Credits</legend>
<div id="credit-after">
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <label>Amount</label>
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[0][amount]" name="credit[0][amount]" placeholder="Amount" value="25,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <label for="exampleInputEmail1">Date</label>
                <input type="date" class="form-control border-input disabled-inputs" id="credit[0][cdate]" name="credit[0][cdate]" placeholder="Date" value="2019-10-09">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <label for="exampleInputEmail1">Details</label>
                <input type="text" class="form-control border-input disabled-inputs" id="credit[0][details]" name="credit[0][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
            <a href="javascript:;" class="credit-transaction-edit"><i class="fa fa-plus icon-add"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[1][amount]" name="credit[1][amount]" placeholder="Amount" value="20,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[1][cdate]" name="credit[1][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[1][details]" name="credit[1][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[2][amount]" name="credit[2][amount]" placeholder="Amount" value="10,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[2][cdate]" name="credit[2][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[2][details]" name="credit[2][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[3][amount]" name="credit[3][amount]" placeholder="Amount" value="20,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[3][cdate]" name="credit[3][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[3][details]" name="credit[3][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <input type="hidden" id="credit_total_rows" name="credit_total_rows" value="4">
</div>

<div id="amount_total">0.00</div>

I need to sum up all the values of all the lines. However, dynamically I add new lines below with this jQuery:

$(document).ready(function() {
$('.money').maskMoney();
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $("#credit-after"); //Fields wrapper
    var add_button      = $(".credit-transaction-edit"); //Add button ID
    var total_debit    = $("#credit_total_rows").val();


    var x = total_debit; //initlal text box count

    add_button.click(function(e){ //on add input button click

        e.preventDefault();

            $(wrapper).append('<div class="note"><div class="col-md-3"><div class="form-group"><input type="text" class="form-control border-input money amount-credit" placeholder="Amount" value="" id="credit['+ x +'][amount]" name="credit['+ x +'][amount]"></div></div><div class="col-md-3"><div class="form-group"><input type="date" class="form-control border-input" placeholder="Date" id="credit['+ x +'][cdate]" name="credit['+ x +'][cdate]"></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control border-input" id="credit['+ x +'][details]" name="credit['+ x +'][details]" placeholder="Details of Transaction"></div></div><div class="col-md-1"><a href="#" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a></div></div></div><div>'); //add input box
            $('.money').maskMoney();

    });

    $(wrapper).on("click",".remove_field_credit_edit", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent().parent().remove(); x--;
    })
}); 

How I can sum up all the values and put a total div?

My idea is that when listing, I already open with autosoma, and later when editing any of the values or adding new line, do the sum.

  • excuse the question, but will be disregarded the fields with date?

  • Yes, I want to add only the values that are in the amount field, which would be the first field of each div. And represent these values below. :)

  • André, make a function somaCampos() that does the work of summing looping and calls her inside the add or remove lines events, so when vc add or delete it redoes the sum.

  • @Wilsonfaustino understood, I just don’t know how to do it. rs

3 answers

2

I suggest you do the function somaCampos(), as below:

function somaCampos(){
    var total = 0;
    $('div#credit-after input[type="text"]').each(function(){ //Você pode identificar melhor os inputs a serem somados aqui!
        let val_input = $(this).val();
        val_input.split(',').join(''); //Limpar os campos - separador de decimal tem que ser o (.)
        total += parseFloat(val_input);
    });

    $('div#amount_total').html(total);
}

somaCampos(); //Soma inicial

This way, your add and remove events would look like this:

Add:

add_button.click(function(e){ //on add input button click
    e.preventDefault();
    $(wrapper).append('<div class="note"><div class="col-md-3"><div class="form-group"><input type="text" class="form-control border-input money amount-credit" placeholder="Amount" value="" id="credit['+ x +'][amount]" name="credit['+ x +'][amount]"></div></div><div class="col-md-3"><div class="form-group"><input type="date" class="form-control border-input" placeholder="Date" id="credit['+ x +'][cdate]" name="credit['+ x +'][cdate]"></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control border-input" id="credit['+ x +'][details]" name="credit['+ x +'][details]" placeholder="Details of Transaction"></div></div><div class="col-md-1"><a href="#" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a></div></div></div><div>'); //add input box
    $('.money').maskMoney();
    somaCampos(); //resomar todos os campos
});

Remove:

$(wrapper).on("click",".remove_field_credit_edit", function(e){ //user click on remove text
    e.preventDefault();
    $(this).parent().parent().remove();
    x--;
    somaCampos(); //resomar todos os campos
})

Thus, when lines are added or removed, the function somaCampos() is again called to recalculate the values.

1

I made the comments in the lines added.

You must create a function to convert this format 25,000.00 on a valid floating, as some friends have done here.

As you were adding a new html, that part <input type="text" class="form-control border-input money amount-credit" placeholder="Amount" value="" id="credit['+ x +'][amount]" name="credit['+ x +'][amount]"> was going with value equal to "", then, that way would always give error in the calculation, because it would try to add a string type value. I added 0.00 to that one inputby default, so it worked perfectly.

Try this code:

 //Função para somar ao carregar a página
function somaCampos(){
 //Faço uma intereção na classe amount-credit
            var amount_credit = document.getElementsByClassName("amount-credit");
            //Cria-se uma variável para add os valores dessa classe
            var totalAmount = 0;
            //Cria-se um loop para interar na classe amount-credit e pegar todos seus 
            //respectivos os valores
            for(let k = 0; k < amount_credit.length; k++){
              
              let value = amount_credit[k].value.split(',').join('');

              totalAmount += parseFloat(value);
            }
          //Mostra o valor total:
            $("#amount_total").html(`R$ ${totalAmount.toFixed(2)}`);
}

$(document).ready(function() {
    $('.money').maskMoney();
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $("#credit-after"); //Fields wrapper
    var add_button      = $(".credit-transaction-edit"); //Add button ID
    var total_debit    = $("#credit_total_rows").val();
    
    //Mostra os valores somados:
    somaCampos();
    
    var x = total_debit; //initlal text box count

    add_button.click(function(e){ //on add input button click

        e.preventDefault();

            $(wrapper).append('<div class="note"><div class="col-md-3"><div class="form-group"><input type="text" class="form-control border-input money amount-credit" placeholder="Amount" value="0.00" id="credit['+ x +'][amount]" name="credit['+ x +'][amount]"x></div></div><div class="col-md-3"><div class="form-group"><input type="date" class="form-control border-input" placeholder="Date" id="credit['+ x +'][cdate]" name="credit['+ x +'][cdate]"></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control border-input" id="credit['+ x +'][details]" name="credit['+ x +'][details]" placeholder="Details of Transaction"></div></div><div class="col-md-1"><a href="#" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a></div></div></div><div>'); //add input box
            $('.money').maskMoney();
            
            //Faço uma intereção na classe amount-credit
            var amount_credit = document.getElementsByClassName("amount-credit");
            //Cria-se uma variável para add os valores dessa classe
            var totalAmount = 0;
            //Cria-se um loop para interar na classe amount-credit e pegar todos seus 
            //respectivos os valores
            for(let k = 0; k < amount_credit.length; k++){
                // console.log(amount_credit[k].value);
              let value = amount_credit[k].value.split(',').join('');

              totalAmount += parseFloat(value);
            }
            //Mostra o valor total:
            //console.log(totalAmount);
            $("#amount_total").html(`R$ ${totalAmount.toFixed(2)}`);


    });

    $(wrapper).on("click",".remove_field_credit_edit", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent().parent().remove(); x--;
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<button class="credit-transaction-edit btn btn-primary">ADD</button>
<div id="amount_total">0.00</div>
<legend>Credits</legend>
<div id="credit-after">
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <label>Amount</label>
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[0][amount]" name="credit[0][amount]" placeholder="Amount" value="25,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <label for="exampleInputEmail1">Date</label>
                <input type="date" class="form-control border-input disabled-inputs" id="credit[0][cdate]" name="credit[0][cdate]" placeholder="Date" value="2019-10-09">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <label for="exampleInputEmail1">Details</label>
                <input type="text" class="form-control border-input disabled-inputs" id="credit[0][details]" name="credit[0][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
            <a href="javascript:;" class="credit-transaction-edit"><i class="fa fa-plus icon-add"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[1][amount]" name="credit[1][amount]" placeholder="Amount" value="20,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[1][cdate]" name="credit[1][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[1][details]" name="credit[1][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[2][amount]" name="credit[2][amount]" placeholder="Amount" value="10,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[2][cdate]" name="credit[2][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[2][details]" name="credit[2][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-3">
            <div class="form-group">
                <input type="text" class="form-control border-input money disabled-inputs amount-credit" id="credit[3][amount]" name="credit[3][amount]" placeholder="Amount" value="20,000.00">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <input type="date" class="form-control border-input disabled-inputs" id="credit[3][cdate]" name="credit[3][cdate]" placeholder="Date" value="2019-10-04">
            </div>
        </div>
        <div class="col-md-5">
            <div class="form-group">
                <input type="text" class="form-control border-input disabled-inputs" id="credit[3][details]" name="credit[3][details]" placeholder="Details of Transaction" value="">
            </div>
        </div>
        <div class="col-md-1" id='credit-transaction-edit'>
            <a href="javascript:;" class="remove_field_edit"><i class="fa fa-trash icon-trash"></i></a>
        </div>
    </div>
    <input type="hidden" id="credit_total_rows" name="credit_total_rows" value="4">
</div>

  • My idea is that when listing, I already open with autosoma, and later when editing any of the values or adding new line, do the sum.

  • I made an issue, check it out.

  • Almost this, however, if I change the value, does not give the result I expect, and also if I add values like 500,000,000.00 would not sum correctly. :/

  • In your example, every time I click on btn add, it shows a different value, and the result should be 75,000.00 that way, as the sum. right?

  • This, but it is because 75,000.00 is not a valid value. You must convert it before making the sum.

  • Yes and then convert again to the original format?

  • I even used this format you gave me, but when adding new field does not add and when changing the value also does not update. :(

  • All right, take the test, please.

Show 3 more comments

1


Create a function that sums the fields. Within the function you use a .each() to go through each field with the class .money and add up the values, but you need to remove the commas from the values as well:

function somaTudo(){
   var total = 0;
   $(".money").each(function(){
      // remove as vígulas e converte o valor para tipo Number
      total += +(this.value.replace(/,/g, ''));
   });
   $("#amount_total").text(total.toLocaleString('en-US', { minimumFractionDigits: 2 }));
}

The last line of the function inserts the sum total into the div #amount_total with the American format, which is the format you are using.

And to change the sum dynamically, just use a system onkeyup calling the function:

$(document).on("keyup", ".money", somaTudo);
  • The only thing I’m weirded out about is him displaying 1 in front of the value...

  • How so?....

  • I’ve already detected, is that on my screen had more items with the money class, but I’ve changed. Thanks, gave it right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.