javascript – How to add cloned events right after cloning

Question:

I have a code that I'm developing, but I'm having 3 difficulties.

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

2nd In the fields totalVenda and totalProfit, carry out the sum of the cloned fields totalreference and profit.

3rd When I clone the lines in the others, I can't do the calculation.

$(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>

Answer:

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

However, you will need to have a declaration of that event first, something like the following:

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