Sum/multiplication of dynamic and total inputs in R$

Asked

Viewed 933 times

3

Good Afternoon, I need a great help, I’m caught in a problem that apparently should be very easy! but I’m not managing to evolve.

I have a code with the following fields: inserir a descrição da imagem aqui

In my script consists of 5 groups of apparent inputs and a button to add more inputs (dynamic inputs), my problem is in the sum of inputs.

1 - I need to multiply the inputs "Quantity" X "Value Und" and its result appear in the input "Total". In my current code this multiplication is already being done, what I need is that the inputs "Quantity" and "Value Und" accept the "," Ex. ( 5,50 ).Because I am working with units of measure and money. (This function should be valid for all fields even the dynamics)

2 - I need to sum all with inputs "Vltotal" ( even the dynamics ) + the input "other" and its result appears in the field "totalnfe". Which should be in Money format R$. Ex( 2.50 or 2.005,50)

As I said, I believe it’s such a simple thing, only I’m not getting it..

Thanks in advance!

<script>
    $(function () {
    //Initialize Select2 Elements
    $(".select2").select2();

    //Date picker
    $('#datae').datepicker({
      format: 'dd/mm/yyyy', 
      todayBtn: 'linked',
      language: 'pt-BR',
      autoclose: true,
      todayHighlight: true
    });
    $('#datav').datepicker({
      format: 'dd/mm/yyyy', 
      todayBtn: 'linked',
      language: 'pt-BR',
      autoclose: true,
      todayHighlight: true
    }); 
  });
</script>
<script type="text/javascript">
$(document).ready(function () {
    var i = 5;
    //adiciona nova linha
    $("#add").on("click", function () {
        i++;
        
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="text" class="form-control" id="cod" name="cod[]"></td>';
        cols += '<td><input type="text" class="form-control" id="desc" name="desc[]"></td>';
        cols += '<td><input type="text" class="form-control" id="und" name="und[]"></td>';
        cols += '<td><input type="text" class="form-control" id="qnd' + i + '" name="qnd[]"></td>';
        cols += '<td><input type="text" class="form-control" id="vlund' + i + '" name="vlund[]"></td>';
        cols += '<td><input type="text" class="form-control soma" id="vltotal' + i + '" name="vltotal[]" onblur="calcular()"></td>';
        cols += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger deleteLinha">X</button></td>';
        newRow.append(cols);
        
        $("#products-table").append(newRow);
    });
    
    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[id^="vlund"], input[id^="qnd"]', function (event) {
        calculateRow($(this).closest("tr"));
    });
    
    //remove linha
    $("#products-table").on("click", "button.deleteLinha", function (event) {
        $(this).closest("tr").remove();
    });
});
 
//função para calcular o total de cada linha   
function calculateRow(row) {
    var vlund = +row.find('input[id^="vlund"]').val();
    var qnd = +row.find('input[id^="qnd"]').val();
    //2 casas decimais
    var total = (vlund * qnd).toFixed(2);
    //substitui ponto por virgula
    total=total.replace(".", ",");
    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('input[id^="vltotal"]').val((total).replace(/\B(?=(\d{3})+(?!\d))/g, "."));     
}

$(".soma").blur(function(){
    calcular();
});

function calcular() {
    var soma = 0;
    $(".soma").each(function(indice, item){
        var valor = parseFloat($(item).val());
        console.log(valor);
        if ( !isNaN( valor ) ) {
            soma += valor;
        }
    });
    $("#totalnfe").val(soma)
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
              <table class="table" id="products-table">             
                <thead>
                  <tr>
                    <th>Cod.</th>
                    <th>Descrição</th>
                    <th>Und.</th>
                    <th>Quantidade</th>
                    <th>R$: UND</th>
                    <th>R$: TOTAL</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td><input type="text" class="form-control cod" id="cod" name="cod[]"></td>
                    <td><input type="text" class="form-control desc" id="desc" name="desc[]"></td>
                    <td><input type="text" class="form-control und" id="und" name="und[]"></td>
                    <td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
                    <td><input type="text" class="form-control" id="vlund" name="vlund[]" onblur="calcular()"></td>
                    <td><input type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()"></td>
                  </tr>
                  <tr>
                    <td><input type="text" class="form-control cod" id="cod" name="cod[]"></td>
                    <td><input type="text" class="form-control desc" id="desc" name="desc[]"></td>
                    <td><input type="text" class="form-control und" id="und" name="und[]"></td>
                    <td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
                    <td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
                    <td><input type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()"></td>
                  </tr>
                  <tr>
                    <td><input type="text" class="form-control" id="cod" name="cod[]"></td>
                    <td><input type="text" class="form-control" id="desc" name="desc[]"></td>
                    <td><input type="text" class="form-control" id="und" name="und[]"></td>
                    <td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
                    <td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
                    <td><input type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()"></td>
                  </tr>                           
                  <tr>
                    <td><input type="text" class="form-control" id="cod" name="cod[]"></td>
                    <td><input type="text" class="form-control" id="desc" name="desc[]"></td>
                    <td><input type="text" class="form-control" id="und" name="und[]"></td>
                    <td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
                    <td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
                    <td><input type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()"></td>
                  </tr>                           
                  <tr>
                    <td><input type="text" class="form-control" id="cod" name="cod[]"></td>
                    <td><input type="text" class="form-control" id="desc" name="desc[]"></td>
                    <td><input type="text" class="form-control" id="und" name="und[]"></td>
                    <td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
                    <td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
                    <td><input type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()"></td>
                  </tr>
                  <tr class="row">
                  </tr>
                </tbody>
                <tfoot>
                  <tr>
                    <td><button type="button" name="add" id="add" class="btn btn-success">Adicionar Linhas +</button></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td><label for="totalnfe">Outras Despesas</label><input type="text" class="form-control" id="outras" name="outras"></td>
                    <td><label for="totalnfe">Valor Total da Nota</label><input type="text" class="form-control" id="totalnfe" name="totalnfe" readonly></td>
                  </tr>  
                </tfoot>
              </table>
              </html>

  • these Date Picker functions are giving error, missing library.

2 answers

3


Comments on the code itself

$(document).ready(function () {
	//chamada da função para calcular valor total
	$(".table").on("change keyup keydown paste propertychange bind mouseover", function(){
	    calcular();
	});

    var i = 5;
    //adiciona nova linha
    $("#add").on("click", function () {
        i++;
        
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="text" class="form-control" id="cod" name="cod[]"></td>';
        cols += '<td><input type="text" class="form-control" id="desc" name="desc[]"></td>';
        cols += '<td><input type="text" class="form-control" id="und" name="und[]"></td>';
        cols += '<td><input type="text" class="form-control" id="qnd' + i + '" name="qnd[]"></td>';
        cols += '<td><input type="text" class="form-control" id="vlund' + i + '" name="vlund[]"></td>';
        cols += '<td><input style="display: none;" type="text" class="form-control soma" id="vltotal' + i + '" name="vltotal[]" onblur="calcular()">';
        cols += '<input type="text" class="form-control somaS" id="vltotalS' + i + '"></td>';
        cols += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger deleteLinha">X</button></td>';
        newRow.append(cols);
        
        $("#products-table").append(newRow);
        
	    	$(".soma").each(function() {
	        	$(this).blur(function(){
	            	calcular();
	        	});
	    	});
	    
    });
    
    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[id^="vlund"], input[id^="qnd"]', function (event) {
        calculateRow($(this).closest("tr"));
    });
    
    //remove linha
    $("#products-table").on("click", "button.deleteLinha", function (event) {
        $(this).closest("tr").remove();
    });
});
 
	//função para calcular o total de cada linha   
        function calculateRow(row) {
	    var vlund = row.find('input[id^="vlund"]').val();
	    //retira separadores de milhar ponto
	    vlund = vlund.split(".").join("");
	    //substitui separador decimal virgula por ponto
	    vlund=vlund.replace(",", ".");
	    vlund = +vlund;
	    var qnd = +row.find('input[id^="qnd"]').val();
	    //total para uso nos calculos
	    //2 casas decimais 
	    var total = (vlund * qnd).toFixed(2);   
	    row.find('input[id^="vltotal"]').val(total); 
	    //totalS para uso na apresentação substitui separador decimal ponto por virgula
	    totalS=total.replace(".", ",");
	    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
	    row.find('input[id^="vltotalS"]').val((totalS).replace(/\B(?=(\d{3})+(?!\d))/g, "."));  
	
	}

	//função para calcular o total da nota 
	function calcular() {
    	var soma = 0;
    	$(".soma").each(function(indice, item){
        	var valor = parseFloat($(item).val());
        	//console.log(valor);
        	if ( !isNaN( valor ) ) {
            	soma += valor;
        	}
    	});
    
    	//pega o valor das outras despesas e caso haja substitue a virgula por ponto
    	var outras = (document.getElementById("outras").value).replace(",", ".");
    
    	outras=Number(outras);
        soma=(soma+outras).toFixed(2);
    	//substitui separador decimal ponto por virgula
    	soma=soma.replace(".", ",");
    	//a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    	$("#totalnfe").val((soma).replace(/\B(?=(\d{3})+(?!\d))/g, "."))
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<table class="table" id="products-table">             
<thead>
<tr>
	<th>Cod.</th>
	<th>Descrição</th>
	<th>Und.</th>
	<th>Quantidade</th>
	<th>R$: UND</th>
	<th>R$: TOTAL</th>
</tr>
</thead>
<tbody>
<tr>
	<td><input type="text" class="form-control cod" id="cod" name="cod[]"></td>
	<td><input type="text" class="form-control desc" id="desc" name="desc[]"></td>
	<td><input type="text" class="form-control und" id="und" name="und[]"></td>
	<td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
	<td><input type="text" class="form-control" id="vlund" name="vlund[]" onblur="calcular()"></td>
	<!-- todos os inputs com style="display: none; são para uso nos calculos-->
	<td><input style="display: none;" type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()">
	<input type="text" class="form-control somaS" id="vltotalS"></td>
</tr>
<tr>
	<td><input type="text" class="form-control cod" id="cod" name="cod[]"></td>
	<td><input type="text" class="form-control desc" id="desc" name="desc[]"></td>
	<td><input type="text" class="form-control und" id="und" name="und[]"></td>
	<td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
	<td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
	<td><input style="display: none;" type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()">
	<input type="text" class="form-control somaS" id="vltotalS"></td>
</tr>
<tr>
	<td><input type="text" class="form-control" id="cod" name="cod[]"></td>
	<td><input type="text" class="form-control" id="desc" name="desc[]"></td>
	<td><input type="text" class="form-control" id="und" name="und[]"></td>
	<td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
	<td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
	<td><input style="display: none;" type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()">
	<input type="text" class="form-control somaS" id="vltotalS"></td>
</tr>                           
<tr>
	<td><input type="text" class="form-control" id="cod" name="cod[]"></td>
	<td><input type="text" class="form-control" id="desc" name="desc[]"></td>
	<td><input type="text" class="form-control" id="und" name="und[]"></td>
	<td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
	<td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
	<td><input style="display: none;" type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()">
	<input type="text" class="form-control somaS" id="vltotalS"></td>
</tr>                           
<tr>
	<td><input type="text" class="form-control" id="cod" name="cod[]"></td>
	<td><input type="text" class="form-control" id="desc" name="desc[]"></td>
	<td><input type="text" class="form-control" id="und" name="und[]"></td>
	<td><input type="text" class="form-control" id="qnd" name="qnd[]"></td>
	<td><input type="text" class="form-control" id="vlund" name="vlund[]"></td>
	<td><input style="display: none;" type="text" class="form-control soma" id="vltotal" name="vltotal[]" onblur="calcular()">
	<input type="text" class="form-control somaS" id="vltotalS"></td>
</tr>

</tbody>
<tfoot>
<tr>
	<td><button type="button" name="add" id="add" class="btn btn-success">Adicionar Linhas +</button></td>
	<td></td>
	<td></td>
	<td></td>
	<td><label for="totalnfe">Outras Despesas</label><input type="text" class="form-control" id="outras" name="outras"></td>
	<td><label for="totalnfe">Valor Total da Nota</label><input type="text" class="total" id="totalnfe" name="totalnfe" readonly></td>
</tr>  
</tfoot>
</table>
</html>

  • Just what I wanted, the only observation is that the input "other" should sum "+" with the sums of the values.

  • @Danillobraga gets smart that is not only change the minus sign (-) in the sum line=(other-sum). toFixed(2); Before that you have to include this line others=Number(others); I already edited the question to add other expenses

  • There is a problem: when you include a value in the format "2.005,50" it gives "Nan" in total.

  • @Dvdsamm only make a replace when picking this value

  • That’s what I thought was complicated. If I do replace in all points, it would not be right tb, because 2.005.50 would turn 200550, because the decimal places, in this case the form, can be separated by both a point and a comma: 5.5 is the same as 5.5, in this case.

  • @Dvdsamm I edited the answer see if you can find something else we can improve

  • It improved, but with number above 1 million gives the "Nan": Ex.: 1,000,000.50... But that doesn’t matter. I misunderstood the question. This formatting he wants in the field "Total Value of Note". Tá certinho your code.

  • @Dvdsamm In this case use Vlund = Vlund.split("."). Join(""); Edited answer These are easy details to correct, it is the will of the user, the best would be to validate the inputs

  • Blz. But if the guy type 1.000.000.50 gives dick. That’s what I was talking about. If the guy type . or , in the decimals, surtisse the same result.

  • @Dvdsamm even in this case there is solution, depends on the will to validate this input, but we have to assume that there must be a certain common sense in the input of a numerical value for the purpose of mathematical calculations, nor calculating machines accept so many points, only accept one point

  • @Leocaracciolo Truth. Even because I find it difficult that they will work with very high values.

  • @Dvdsamm hahaha, if you are a user from Brasilia we will have to correct the code

  • @Leocaracciolo I’m from Brasilia, but in my case I find it hard to even use numbers with 3 digits rsrs...

  • @Dvdsamm gives me the number of your account and PASSWORD that I will deposit some for you :)

  • Dude, I just can’t give it to you 'cause you’re gonna want to take out my eight bucks you got there.

Show 10 more comments

0

One suggestion is to use the input id to take input values, multiply them and use the following code to format:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

Browser other questions tagged

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