Calculation between inputs in table with dynamic line creation

Asked

Viewed 23 times

1

I’m setting up a table where lines are created dynamic, on these lines I’m doing a field multiplication Qtde * VlrUnitVista and playing the value on the field VlrTotalVista and is working well, in the first line, in the following lines the calculations are not being made, how to adapt the code I have, code taken from the site of William Bruno, so that calculations can also be made on the lines to be inserted? Another difficulty I found was that I also need to do the calculation of Qtde * VlrUnitPrazo and play the value on the field VlrTotalPrazo, I did some tests changing the name of some functions and even duplicate them, but no chances.

The form I have is like this:

<form id="formulario" action="" method="post" >
     <div id="mensagem" class=""></div>

        <div class="table-responsive">
           <table width="100%" class="table table-hover table-bordered" id="products-table">
              <tbody>
                 <tr>
                     <th colspan="6" rowspan="2">&nbsp;</th>
                     <th colspan="4" class="actions">Unidade</th>
                     <th class="actions">&nbsp;</th>
                  </tr>
                 <tr>
                     <th colspan="2" class="actions">A vista</th>
                     <th colspan="2" class="actions">A prazo</th>
                     <th class="actions">&nbsp;</th>
                 </tr>
                 <tr>
                   <th width="12%">Produto</th>
                    <th width="12%">Embalagem</th>
                    <th width="12%">Concorrência</th>
                    <th width="10%">Fonte</th>
                    <th width="10%">Frete</th>
                    <th width="10%">Qtde</th>
                    <th colspan="2" class="actions">Unitário</th>
                    <th colspan="2" class="actions">Total</th>
                    <th width="18%" class="actions">Ações</th>
                 </tr>
                 <tr>
                    <td width="12%"><input id="Produto" name="Produto[]" type="text" size="10" ></td>                        
                    <td width="12%"><input id="Embalagem" name="Embalagem[]" type="text" size="10"></td>
                    <td width="12%"><input id="Concorrencia" name="Concorrencia[]" type="text" size="10"></td>
                    <td width="10%"><input id="Fonte" name="Fonte[]" type="text" value="Produtor" size="10"></td>
                    <td width="10%"><input id="Frete" name="Frete[]" type="text" value="CIF" size="10"></td>
                    <td width="10%"><input id="Qtde" name="Qtde[]" type="text" size="10"></td>
                    <td width="11%"><input id="VlrUnitVista" name="VlrUnitVista[]" type="text" size="10"></td>
                    <td width="6%"><input  id="VlrTotalVista" name="VlrTotalVista[]" type="text" size="10"></td>
                    <td width="8%"><input  id="VlrUnitPrazo[]" name="VlrUnitPrazo[]" type="text" size="10"></td>
                    <td width="8%"><input  id="VlrTotalPrazo[]"  name="VlrTotalPrazo[]" type="text" size="10"></td>                        
                    <td class="actions">
                       <button class="btn btn-large btn-danger btn-xs" onclick="RemoveTableRow(this)" type="button">Remover</button>
                   </td>
                 </tr>
              </tbody>
              <tfoot>
                 <tr>
                    <td colspan="11" style="text-align: left;">
                       <button class="btn btn-large btn-success" onclick="AddTableRow(this)" type="button">Adicionar Linha</button>
                    </td>
                 </tr>
              </tfoot>
           </table>
        </div>

The creation of dynamic table lines are like this:

(function($) {
   
    RemoveTableRow = function(handler) {
      var tr = $(handler).closest('tr');
   
      tr.fadeOut(400, function(){ 
        tr.remove(); 
      }); 
   
      return false;
    };
    
    AddTableRow = function() {
        
        var newRow = $("<tr>");
        var cols = "";
        
		cols += '<td><input type="text" id="Produto" name="Produto[]" value="" size="10"></td>';
        cols += '<td><input type="text" id="Embalagem" name="Embalagem[]" size="10"></td>';
        cols += '<td><input type="text" id="Concorrencia" name="Concorrencia[]" size="10"></td>';
        cols += '<td><input type="text" id="Fonte" name="Fonte[]" size="10" value="Produtor"></td>';
        cols += '<td><input type="text" id="Frete" name="Frete[]" size="10" value="CIF"></td>';
		cols += '<td><input type="text" id="Qtde" name="Qtde[]" size="10"></td>';
        cols += '<td><input type="text" id="VlrUnitVista" name="VlrUnitVista[]" size="10"></td>';
        cols += '<td><input type="text" id="VlrTotalVista" name="VlrTotalVista[]" size="10"></td>';
        cols += '<td><input type="text" id="VlrUnitPrazo" name="VlrUnitPrazo[]" size="10"></td>';
        cols += '<td><input type="text" id="VlrTotalPrazo" name="VlrTotalPrazo[]" size="10"></td>';
        		
        
        cols += '<td class="actions">';
        cols += '<button class="btn btn-large btn-danger btn-xs" onclick="RemoveTableRow(this)" type="button">Remover</button>';
        cols += '</td>';
        
        newRow.append(cols);
        
        $("#products-table").append(newRow);
      
        return false;
    };
    
   })(jQuery);

And the calculations are being made using this:

	function id(el) {
	  return document.getElementById(el);
	}

	function total( Qtde, VlrUnitVista ) {
	  return parseFloat(Qtde.replace(',', '.'), 10) * parseFloat(VlrUnitVista.replace(',', '.'), 10);
	}

	window.onload = function() {
	  id('Qtde').addEventListener('keyup', function() {
		var result = total( this.value , id('VlrUnitVista').value );
		id('VlrTotalVista').value = String(result.toFixed(2)).formatMoney();
	  });

	  id('VlrUnitVista').addEventListener('keyup', function(){
		var result = total( id('Qtde').value , this.value );
		id('VlrTotalVista').value = String(result.toFixed(2)).formatMoney();
	  });
	}
	


	String.prototype.formatMoney = function() {
	  var v = this;

	  if(v.indexOf('.') === -1) {
		v = v.replace(/([\d]+)/, "$1,00");
	  }

	  v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
	  v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
	  v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

	  return v;
	};

I’m posting the image of my form, if it helps.

inserir a descrição da imagem aqui

1 answer

1


When using id in the fields, you will duplicate the same ids when creating dynamic lines. Besides being wrong (a id must be unique on the page) you will not be able to get the values of the fields. It is necessary to exchange all the ids of the fields by class.

Another point is: since you are using jQuery, it makes no sense to mix pure Javascript using window.onload and addEventListener. Include the events keyup within the function (function($){.

What I did was convert the events addEventListener in jQuery format that will capture the values in the dynamic lines. Also, it was necessary to create another event for the values of the column "In time":

$(document).on("keyup", ".Qtde", function(){
   var result = total( $(this).val() , $(this).closest("tr").find(".VlrUnitVista").val() );
   if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalVista").val(String(result.toFixed(2)).formatMoney());
});

$(document).on("keyup", ".VlrUnitVista", function(){
   var result = total( $(this).closest("tr").find(".Qtde").val() , $(this).val() );
   if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalVista").val(String(result.toFixed(2)).formatMoney());
});

$(document).on("keyup", ".VlrUnitPrazo", function(){
   var result = total( $(this).closest("tr").find(".Qtde").val() , $(this).val() );
   if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalPrazo").val(String(result.toFixed(2)).formatMoney());
});

So the code went like this:

(function($) {
   
    RemoveTableRow = function(handler) {
      var tr = $(handler).closest('tr');
   
      tr.fadeOut(400, function(){ 
        tr.remove(); 
      }); 
   
      return false;
    };
    
    AddTableRow = function() {
        
        var newRow = $("<tr>");
        var cols = "";
        
		cols += '<td><input type="text" class="Produto" name="Produto[]" value="" size="10"></td>';
        cols += '<td><input type="text" class="Embalagem" name="Embalagem[]" size="10"></td>';
        cols += '<td><input type="text" class="Concorrencia" name="Concorrencia[]" size="10"></td>';
        cols += '<td><input type="text" class="Fonte" name="Fonte[]" size="10" value="Produtor"></td>';
        cols += '<td><input type="text" class="Frete" name="Frete[]" size="10" value="CIF"></td>';
		cols += '<td><input type="text" class="Qtde" name="Qtde[]" size="10"></td>';
        cols += '<td><input type="text" class="VlrUnitVista" name="VlrUnitVista[]" size="10"></td>';
        cols += '<td><input type="text" class="VlrTotalVista" name="VlrTotalVista[]" size="10"></td>';
        cols += '<td><input type="text" class="VlrUnitPrazo" name="VlrUnitPrazo[]" size="10"></td>';
        cols += '<td><input type="text" class="VlrTotalPrazo" name="VlrTotalPrazo[]" size="10"></td>';
        		
        
        cols += '<td class="actions">';
        cols += '<button class="btn btn-large btn-danger btn-xs" onclick="RemoveTableRow(this)" type="button">Remover</button>';
        cols += '</td>';
        
        newRow.append(cols);
        
        $("#products-table").append(newRow);
      
        return false;
    };

   $(document).on("keyup", ".Qtde", function(){
		var result = total( $(this).val() , $(this).closest("tr").find(".VlrUnitVista").val() );
		if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalVista").val(String(result.toFixed(2)).formatMoney());
   });

   $(document).on("keyup", ".VlrUnitVista", function(){
		var result = total( $(this).closest("tr").find(".Qtde").val() , $(this).val() );
		if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalVista").val(String(result.toFixed(2)).formatMoney());
   });

   $(document).on("keyup", ".VlrUnitPrazo", function(){
		var result = total( $(this).closest("tr").find(".Qtde").val() , $(this).val() );
		if(!isNaN(result)) $(this).closest("tr").find(".VlrTotalPrazo").val(String(result.toFixed(2)).formatMoney());
   });


})(jQuery);
   
   function id(el) {
	  return document.getElementById(el);
	}

	function total( Qtde, VlrUnitVista ) {
	  return parseFloat(Qtde.replace(',', '.'), 10) * parseFloat(VlrUnitVista.replace(',', '.'), 10);
	}


	String.prototype.formatMoney = function() {
	  var v = this;

	  if(v.indexOf('.') === -1) {
		v = v.replace(/([\d]+)/, "$1,00");
	  }

	  v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
	  v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
	  v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

	  return v;
	};
table { 
   table-layout: fixed; 
   border-collapse: collapse; 
} 

th { 
   border: 1px solid #000; 
   font-family: Verdana, Arial, sans-serif; 
   font-size: 0.8em; 
   background-color: #009fef; 
   padding: 0px 5px 0px 5px; 
} 

td { 
   border: 1px solid #000; 
   font-family: Verdana, Arial, sans-serif; 
   font-size: 0.8em; 
   padding: 0px 5px 0px 5px; 
} 

.centro { 
   text-align: center; 
} 

.cinzaClaro { 
   background-color: #CACACA; 
} 

.cinzaEscuro { 
   background-color: #EBEBEB; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formulario" action="" method="post" >
     <div id="mensagem" class=""></div>

        <div class="table-responsive">
           <table width="100%" class="table table-hover table-bordered" id="products-table">
              <tbody>
                 <tr>
                     <th colspan="6" rowspan="2">&nbsp;</th>
                     <th colspan="4" class="actions">Unidade</th>
                     <th class="actions">&nbsp;</th>
                  </tr>
                 <tr>
                     <th colspan="2" class="actions">A vista</th>
                     <th colspan="2" class="actions">A prazo</th>
                     <th class="actions">&nbsp;</th>
                 </tr>
                 <tr>
                   <th width="12%">Produto</th>
                    <th width="12%">Embalagem</th>
                    <th width="12%">Concorrência</th>
                    <th width="10%">Fonte</th>
                    <th width="10%">Frete</th>
                    <th width="10%">Qtde</th>
                    <th colspan="2" class="actions">Unitário</th>
                    <th colspan="2" class="actions">Total</th>
                    <th width="18%" class="actions">Ações</th>
                 </tr>
                 <tr>
                    <td width="12%"><input class="Produto" name="Produto[]" type="text" size="10" ></td>                        
                    <td width="12%"><input class="Embalagem" name="Embalagem[]" type="text" size="10"></td>
                    <td width="12%"><input class="Concorrencia" name="Concorrencia[]" type="text" size="10"></td>
                    <td width="10%"><input class="Fonte" name="Fonte[]" type="text" value="Produtor" size="10"></td>
                    <td width="10%"><input class="Frete" name="Frete[]" type="text" value="CIF" size="10"></td>
                    <td width="10%"><input class="Qtde" name="Qtde[]" type="text" size="10"></td>
                    <td width="11%"><input class="VlrUnitVista" name="VlrUnitVista[]" type="text" size="10"></td>
                    <td width="6%"><input  class="VlrTotalVista" name="VlrTotalVista[]" type="text" size="10"></td>
                    <td width="8%"><input  class="VlrUnitPrazo" name="VlrUnitPrazo[]" type="text" size="10"></td>
                    <td width="8%"><input  class="VlrTotalPrazo"  name="VlrTotalPrazo[]" type="text" size="10"></td>                        
                    <td class="actions">
                       <button class="btn btn-large btn-danger btn-xs" onclick="RemoveTableRow(this)" type="button">Remover</button>
                   </td>
                 </tr>
              </tbody>
              <tfoot>
                 <tr>
                    <td colspan="11" style="text-align: left;">
                       <button class="btn btn-large btn-success" onclick="AddTableRow(this)" type="button">Adicionar Linha</button>
                    </td>
                 </tr>
              </tfoot>
           </table>
        </div>
   </div>
</form>

  • Fantastic @dvd, thank you so much for the excellent code.

Browser other questions tagged

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