Calculation between table inputs with creation of dynamic lines

1
I'm building a table where the rows are dynamically created, on these rows I'm doing a multiplication of the field Qtde * VlrUnitVista and throwing the value in the field VlrTotalVista and is working well, in the first row, in the following rows the calculations are not being done, how to adapt the code that I have, code that I get from the William Bruno site, so that the calculations can also be performed on the lines to be inserted? Another difficulty I encountered was that I also need to compute Qtde * VlrUnitPrazo and play the value in the VlrTotalPrazo field, I made some tests changing the name of some functions and even duplicating them, / p>

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 rows in the table looks 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 done 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.

    
asked by anonymous 23.02.2018 / 14:15

1 answer

1

When you use id in the fields, you will duplicate the same ids when creating dynamic rows. In addition to being wrong ( id must be unique on the page) you will not be able to get field values. You need to change all% of fields by% with%.

Another point is: since you are using jQuery, it does not make sense to mix pure JavaScript using ids and class . Include events window.onload within function addEventListener .

What I did was convert the keyup events to jQuery format which will capture the values in the dynamic rows. In addition, it was necessary to create another event for the values of the column "On 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 looks 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><formid="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>
    
23.02.2018 / 14:46