How to add cloned events, right after cloning

Asked

Viewed 246 times

3

I have a code I’m developing, but I’m encountering 3 difficulties.

1st I would like to make a calculation of 11% + the cost.

2nd In the fields totalVenda and totalLucro realize all the sum of the cloned fields totalreferenced and profit.

3rd When I clone the lines in the others I cannot calculate.

$(document).ready(function() {
  var $adicionarCampo = $(".adicionarCampo");

  function removeCampo() {
    $(".removerCampo").off("click");
    $(".removerCampo").on("click", function() {
      if ($("div.tabelasDuplicar").length > 1) {
        $(this).parents("div.tabelasDuplicar").remove();
      }
    });
  }

  $adicionarCampo.on('click', function() {
    novoCampo = $("div.tabelasDuplicar:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("div.tabelasDuplicar:last");
    removeCampo();
  });

  $('input[name="qty[]"]').keyup(calcTotal);
  $('input[name="UnitValRef[]"]').keyup(calcTotal);
  $('input[name="custoUnit[]"]').keyup(calcTotal);
  $('input[name="custoImposto[]"]').keyup(calcLucro);

  $('input[name="UnitValRef[]"]').on('keyup', maskMoney)
  $('input[name="custoUnit[]"]').on('keyup', maskMoney)
  $('input[name="custoImposto[]"]').on('keyup', maskMoney)
  $('input[name="custoTotal[]"]').on('keyup', maskMoney)
  $('input[name="valorTotalRef[]"]').on('keyup', maskMoney)
  $('input[name="lucro[]"]').on('keyup', maskMoney)

});

var calcLucro = function(event) {
  var $lucro = $('input[name="lucro[]"]')
  var imposto = $('input[name="custoImposto[]"]').val().toFloat() || 0;
  var custo = $('input[name="valorTotalRef[]"]').val().toFloat() || 0;

  var total = custo - imposto;
  $lucro.val(String(total.toFixed(2)).formatMoney());
};

var calcTotal = function(event) {
  var qty = $('input[name="qty[]"]').val().toFloat() || 0;
  var ref = $('input[name="UnitValRef[]"]').val().toFloat() || 0;
  var unit = $('input[name="custoUnit[]"]').val().toFloat() || 0;

  var totalRef = qty * ref;
  var totalCusto = qty * unit;
  $('input[name="valorTotalRef[]"]').val(String(totalRef.toFixed(2)).formatMoney());
  $('input[name="custoTotal[]"]').val(String(totalCusto.toFixed(2)).formatMoney());
};

var maskMoney = function(event) {
  var $this = $(this);
  mascara($this, mvalor);
};

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;
};
String.prototype.toFloat = function() {
  var v = this;

  if (!v) return 0;
  return parseFloat(v.replace(/[\D]+/g, '').replace(/([\d]+)(\d{2})$/, "$1.$2"), 10);
};

function mascara(o, f) {
  v_obj = o
  v_fun = f
  setTimeout(execmascara, 1);
}

function execmascara() {
  v_obj.val(v_fun(v_obj.val()))
}

function mvalor(v) {
  v = v.replace(/\D/g, "");
  v = v.replace(/(\d)(\d{8})$/, "$1.$2");
  v = v.replace(/(\d)(\d{5})$/, "$1.$2");

  v = v.replace(/(\d)(\d{2})$/, "$1,$2");
  return v;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css' />
  <link href='http://fonts.googleapis.com/css?family=Terminal+Dosis' rel='stylesheet' type='text/css' />

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

</head>

<body>
  <form name="frmEnviar" action="" method="post">

    <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
      <tr>
        <td height="46" colspan="12" class="cabecario">CADASTRO DE LICITAÇÕES</td>
      </tr>
      <tr>
        <th height="4" colspan="12" scope="col">&nbsp;</th>
      </tr>
      <tr class="linha1">
        <td width="40">Orgão</td>
        <td width="43">UASG</td>
        <td width="47">Pregão</td>
        <td width="44">Objeto</td>
        <td width="51">Abertura</td>
        <td width="71">U.F.</td>
        <td width="121">Tipo Licitação</td>
        <td width="144">Situação</td>
        <td width="68">Finalizado</td>
        <td width="98">Anexar arquivo</td>
        <td width="79">Total Venda</td>
        <td width="79">Total Lucro</td>
      </tr>
      <tr>
        <td>
          <label></label>
          <input type="text" name="orgao" class="txt bradius" size="27" style="font-size: 10pt" />
        </td>
        <td>
          <label></label>
          <input type="text" name="uasg" class="txt bradius" size="4" style="text-align: center;" />
        </td>
        <td>
          <label></label>
          <input type="text" name="pregao" class="txt bradius" size="4" style="text-align: center;" />
        </td>
        <td>
          <label></label>
          <input type="text" name="objeto" class="txt bradius" size="37" />
        </td>
        <td>
          <label></label>
          <input type="text" name="abertura" class="txt bradius" size="16" style="text-align: center;" OnKeyPress="return mascaraGenerica(event, this, '##/##/####');" placeholder="DD/MM/YYYY" />
        </td>
        <td>
          <select name="situacao[]">
            <option value="" selected="selected">...</option>
            <option value="AC">AC</option>
            <option value="AL">AL</option>
            <option value="AP">AP</option>
            <option value="AM">AM</option>
            <option value="BA">BA</option>
            <option value="CE">CE</option>
            <option value="DF">DF</option>
            <option value="ES">ES</option>
            <option value="GO">GO</option>
            <option value="MA">MA</option>
            <option value="MT">MT</option>
            <option value="MS">MS</option>
            <option value="MG">MG</option>
            <option value="PA">PA</option>
            <option value="PB">PB</option>
            <option value="PR">PR</option>
            <option value="PE">PE</option>
            <option value="PI">PI</option>
            <option value="RJ">RJ</option>
            <option value="RN">RN</option>
            <option value="RS">RS</option>
            <option value="RO">RO</option>
            <option value="RR">RR</option>
            <option value="SC">SC</option>
            <option value="SP">SP</option>
            <option value="SE">SE</option>
            <option value="TO">TO</option>
          </select>
        </td>
        <td>
          <select name="tipolicitacao[]">
            <option value="" selected="selected">Selecione...</option>
            <option value="Servico">Serviço</option>
            <option value="Informatica">Informática</option>
            <option value="Eletronico">Eletrônico</option>
            <option value="Outros">Outros</option>
          </select>
        </td>
        <td>
          <select name="situacao[]">
            <option value="" selected="selected">Selecione...</option>
            <option value="Agendado">Agendado</option>
            <option value="Acompanhar">Acompanhar</option>
            <option value="EmAndamento">Em Andamento</option>
            <option value="Suspensao">Suspensão</option>
            <option value="Ganho">Ganho</option>
            <option value="NaoGanho">Não Ganho</option>
          </select>
        </td>
        <td>
          <label></label>
          <input type="text" name="finalizado" class="txt bradius" size="16" style="text-align: center;" OnKeyPress="return mascaraGenerica(event, this, '##/##/####');" placeholder="DD/MM/YYYY" />
        </td>
        <td>&nbsp;</td>
        <td>
          <label></label>
          <input type="text" name="totalVenda" class="txt bradius" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" />
        </td>
        <td>
          <label></label>
          <input type="text" name="totalLucro" class="txt bradius" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" />
        </td>
      </tr>
    </table>

    <br />

    <div class="tabelasDuplicar" style="border-bottom: 1px dashed #f1f1f1;padding: 10px 0;" align="center">
      <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
        <tr class="linha1">
          <td>ID</td>
          <td>Item</td>
          <td>Material</td>
          <td>Quantidade</td>
          <td>Referência</td>
          <td>Total Referência</td>
          <td>C. Unitário</td>
          <td>Custo Total</td>
          <td>Custo Imposto</td>
          <td>Lucro</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td>
            <label></label>
            <input type="text" name="ID[]" class="txt bradius" size="1" />
          </td>
          <td>
            <label></label>
            <input type="text" name="item[]" class="txt bradius" size="1" / OnKeyPress="return mascaraGenerica(event, this, '####');">
          </td>
          <td>
            <label></label>
            <input type="text" name="descricao[]" class="txt bradius" size="40" />
          </td>
          <td>
            <label></label>
            <input type="text" name="qty[]" class="txt bradius" value="" size="7" style="text-align: center;">
          </td>
          <td>
            <label></label>
            <input type="text" name="UnitValRef[]" class="txt bradius" value="" size="17" style="text-align: center;" placeholder="R$ 0,00">
          </td>
          <td>
            <label></label>
            <input type="text" name="valorTotalRef[]" class="txt bradius" value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00">
          </td>
          <td>
            <label></label>
            <input type="text" name="custoUnit[]" value="" class="txt bradius" size="7" style="text-align: center;" placeholder="R$ 0,00" />
          </td>
          <td>
            <label></label>
            <input type="text" name="custoTotal[]" class="txt bradius" value="" size="10" readonly="readonly" style="text-align: center;" placeholder="R$ 0,00" />
          </td>
          <td>
            <label></label>
            <input type="text" name="custoImposto[]" value="" class="txt bradius" size="10" style="text-align: center;" placeholder="R$ 0,00" />
          </td>
          <td>
            <label></label>
            <input type="text" name="lucro[]" class="txt bradius" value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00" />
          </td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
      </table>

      <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
        <tbody>
          <tr class="linha1">
            <td>Fornecedor</td>
            <td>Prazo Fornecedor</td>
            <td>Prazo Cliente</td>
            <td>Transportadora</td>
            <td>Observação</td>
            <td>&nbsp;</td>
            <td>Status</td>
            <td>Motivo</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td>
              <label></label>
              <input type="text" name="fornecedor[]" class="txt bradius" size="5" />
            </td>
            <td>
              <label></label>
              <input type="text" name="prazoFornecedor[]" class="txt bradius" size="11" style="text-align: center;" />
            </td>
            <td>
              <label></label>
              <input type="text" name="prazoCliente[]" class="txt bradius" size="7" style="text-align: center;" />
            </td>
            <td>
              <label></label>
              <input type="text" name="transportadora[]" class="txt bradius" size="9" />
            </td>
            <td>
              <label></label>
              <input type="text" name="observacao[]" class="txt bradius" size="47" />
            </td>
            <td>&nbsp;</td>
            <td>
              <label></label>
              <input type="text" name="status[]" class="txt bradius" size="10" />
            </td>
            <td>
              <label></label>
              <input type="text" name="motivo[]" class="txt bradius" size="10" />
            </td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class="actions">
              <button class="btn btn-large btn-danger removerCampo" type="button" id="btn-remove">Remover</button>
            </td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- botao adicionar -->
    <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
      <tr>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>
          <button class="btn btn-large btn-success adicionarCampo" type="button" id="btn-adiciona">Adicionar Produto</button>
          <button class="btn btn-large" type="submit">CADASTRAR</button>
        </td>
      </tr>
    </table>

  </form>
</body>

</html>

  • 11% of what ? For the event to work you should assign the event in div, which is who is actually being cloned: $("div.tabelasDuplicar").on("keyup", 'input[name="qty[]"], input[name="UnitValRef[]"], input[name="custoUnit[]"], input[name="custoImposto[]"]', function()

  • Hello, the 11% would be the interest of the total cost. I did not understand how I have to assign in DIV, I am new and I have no knowledge.!

2 answers

1

you can use novoCampo = $("div.tabelasDuplicar:first").clone(true); (notice the true) clone(true) will also clone the events that this div has binded;

However, you will first have to have a statement of that event, something like the below:

<div class="click-me hide">click</div>
$('.click-me').on('click',....)
var newEle = $('.click-me').clone(true);
newEle.appendTo('body');

0

Matthew, I know the code below won’t solve your problem, but it might help you organize the code.

In this case, I have a class that closes the Line, so I can access its properties directly, as well as properties to access (get/set) the values already as int/float:

var tabela = document.querySelector("#tabela tbody");
var incluirLinha = document.getElementById("incluirLinha");

//template para criação da linha
var tmplLinha = document.getElementById("tmplLinha").content;

//classe criada para fazer o closure da nova linha;
var Linha = function (row) {
  var self = this;
  this.inputs = {};
  this.inputs.ID = row.querySelector('input[name="ID[]"]');
  this.inputs.item = row.querySelector('input[name="item[]"]');
  this.inputs.descricao = row.querySelector('input[name="descricao[]"]');
  this.inputs.qty = row.querySelector('input[name="qty[]"]');
  this.inputs.UnitValRef = row.querySelector('input[name="UnitValRef[]"]');
  this.inputs.valorTotalRef = row.querySelector('input[name="valorTotalRef[]"]');  
  this.inputs.custoUnit = row.querySelector('input[name="custoUnit[]"]');
  this.inputs.custoTotal = row.querySelector('input[name="custoTotal[]"]');
  this.inputs.custoImposto = row.querySelector('input[name="custoImposto[]"]');
  this.inputs.lucro = row.querySelector('input[name="lucro[]"]');

  var calcTotal = function (event) { self.calcTotal(event); };
  var calcLucro = function (event) { self.calcLucro(event); };

  this.inputs.qty.addEventListener("input", calcTotal);
  this.inputs.UnitValRef.addEventListener("input", calcTotal);
  this.inputs.custoUnit.addEventListener("input", calcTotal);  

  this.inputs.qty.addEventListener("input", calcLucro);
  this.inputs.UnitValRef.addEventListener("input", calcLucro);
  this.inputs.custoImposto.addEventListener("input", calcLucro);
}

var props = {};
props.Int = ["ID", "qty"];
props.String = ["item", "descricao"];
props.Float = ["UnitValRef", "valorTotalRef", "custoUnit", "custoTotal", "custoImposto", "lucro"];

//get para as propriedades com valor esperado do tipo int;
props.Int.forEach(function (prop, indice) {
  Object.defineProperty(Linha.prototype, prop, {
    get: function() { return parseInt(this.inputs[prop].value) || 0; },
    set: function(value) { this.inputs[prop].value = value; }
  });
});

//get para as propriedades com valor esperado do tipo string;
props.String.forEach(function (prop, indice) {
  Object.defineProperty(Linha.prototype, prop, {
    get: function() { return this.inputs[prop].value; },
    set: function(value) { this.inputs[prop].value = value; }
  });
});

//get para as propriedades com valor esperado do tipo float;
props.Float.forEach(function (prop, indice) {
  Object.defineProperty(Linha.prototype, prop, {
    get: function() { return parseFloat(this.inputs[prop].value) || 0; },
    set: function(value) { this.inputs[prop].value = value; }
  });
});

//calculo do valor total
Linha.prototype.calcTotal = function (event) { 
  this.valorTotalRef = this.qty * this.UnitValRef;
  this.custoTotal = this.qty * this.custoUnit;
}

//calculo do valor do lucro
Linha.prototype.calcLucro = function (event) {
  this.lucro = this.valorTotalRef - this.custoImposto;
}

//incluindo nova linha;
incluirLinha.addEventListener("click", function (event) {
  var row = document.importNode(tmplLinha, true);
  var linha = new Linha(row);
  tabela.appendChild(row);
});
<table id="tabela">
  <thead>
    <tr>
      <th>ID</th>
      <th>Item</th>
      <th>Material</th>
      <th>Quantidade</th>
      <th>Referência</th>
      <th>Total Referência</th>
      <th>C. Unitário</th>
      <th>Custo Total</th>
      <th>Custo Imposto</th>
      <th>Lucro</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <td colspan="12">
        <input id="incluirLinha" type="button" value="Incluir Linha" />
      </td>
    </tr>
  </tfoot>
  <tbody>
    
  </tbody>
</table>

<!-- Template para uma nova linha -->
<template id="tmplLinha">
  <tr>
    <td>
      <label>
        <input type="text" name="ID[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="item[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="descricao[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="qty[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="UnitValRef[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="valorTotalRef[]" readonly />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="custoUnit[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="custoTotal[]" readonly />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="custoImposto[]" />
      </label>      
    </td>
    <td>
      <label>
        <input type="text" name="lucro[]" readonly />
      </label>      
    </td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</template>

Browser other questions tagged

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