Addition / multiplication of dynamic inputs and total in R $

4

Good afternoon, I need a great help, I'm stuck in a problem that apparently must be very easy! but I can not evolve.

I have a code with the following fields:

Inmyscriptthereare5groupsofapparentinputsandabuttontoaddmoreinputs(dynamicinputs),myproblemisthesumofinputs.

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

2 - I need to sum all of them with "Vltotal" (even the dynamic) inputs + the "other" input and their result appears in the "totalnfe" field. That should be in format of Money R $. Ex (2.50 or 2,005.50)

As I said, I think it's such a simple thing, I just can not do it.

Thank you 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><tableclass="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>
    
asked by anonymous 31.08.2017 / 22:29

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><tableclass="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>
    
01.09.2017 / 13:23
0

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

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