How to add values from a td column dynamically with jquery?

0

I have a payment system that takes the total value of the purchase and divides it into the number of parcels requested by the customer, and these parcels can have their value changed dynamically, since the customer can give a larger or smaller input value, until all good.

The problem is that I have to change the value of the parcel to the parcel manually, I wanted to change the value of the first parcel and the others to adjust, keeping the total value in the sum.

  

Let's take an example:

If the total purchase is $ 10,000.00 and the customer decides to install 4X equals, each installment would be $ 2,500.00, but if the customer decides to give a smaller or larger installment in the first as an entrance, the other installments should be adjusted, for example the entry was R $ 2,000.00, so the other 3 installments should adjust with the remaining amount of the total that would be each remaining installment of R $ 2,666.66.

Here's the table:

Belowisanoutlineofthecodetobetterunderstand.

$(document).on('click', function() {
  $('#table_com_parcelas tbody tr').each(function(i) {
    $(this).children('td').each(function(p) {
      if (($(this).attr('title') === 'valor') || $(this).attr('title') === 'vencimento') {
        $(this).dblclick(function() { //inicio dblclick

          if ($('td > input').length > 0) {
            return;
          }

          var conteudoOriginal = $(this).text();
          var novoElemento = $('<input/>', {
            type: 'text',
            value: conteudoOriginal
            // blur: somaTds()

          });
          if ($(this).attr('title') === 'valor') {
            $(novoElemento).maskMoney({
              prefix: 'R$ ',
              allowNegative: true,
              thousands: '.',
              decimal: ',',
              affixesStay: true
            });
          }
          if ($(this).attr('title') === 'vencimento') {
            $(novoElemento).mask("99/99/9999");
          }

          $(this).html(novoElemento.bind('blur keydown', function(e) {
            var keyCode = e.which;
            var conteudoNovo = $(this).val();
            if (keyCode == 13 || keyCode == 9 || keyCode == 0 && conteudoNovo != '' && conteudoNovo != conteudoOriginal) {
              var objeto = $(this);
              $.ajax({
                type: "POST",
                url: "#",
                data: {
                  id: $(this).parents('tr').children().first().text(),
                  campo: $(this).parent().attr('title'),
                  valor: conteudoNovo
                },
                success: function(result) {
                  objeto.parent().html(conteudoNovo);
                  $('#valor_total').text(result);
                }
              });

              var posicao = p + 1;
              $(this).parent()
                .html(conteudoNovo)
                .parents('tr')
                .next()
                .children('td:nth-child(' + posicao + ')')
                .trigger('dblclick');

            } else if (keyCode == 27 || e.type == 'blur')
              $(this).parent().html(conteudoOriginal);
          }));
          $(this).children().select();
        } /*fim dblclick*/ );
      };
    });
  });
});
<script src="https://code.jquery.com/jquery-3.2.1.js"integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<table id="table_com_parcelas" class="table table-condensed">
  <thead>
    <tr>
      <th class="align">Parcela</th>
      <th class="align">Vencimento</th>
      <th class="align">Valor</th>
      <th class="align">Forma pagamento</th>
    </tr>
  </thead>
  <tbody>
    <tr id="row-1">
      <td class="align">1 de 3</td>
      <td title="vencimento" class="align">24/10/2017</td>
      <td title="valor" class="align">R$ 13.333,33</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-1" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-1" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-1"></span>
          </form>
        </div>
      </td>
    </tr>
    <tr id="row-2">
      <td class="align">2 de 3</td>
      <td title="vencimento" class="align">24/11/2017</td>
      <td title="valor" class="align">R$ 13.333,33</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-2" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-2" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-2"></span>
          </form>
        </div>
      </td>
    </tr>
    <tr id="row-3">
      <td class="align">3 de 3</td>
      <td title="vencimento" class="align">24/12/2017</td>
      <td title="valor" class="align">R$ 13.333,33</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-3" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-3" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-3"></span>
          </form>
        </div>
      </td>
    </tr>
  </tbody>
</table>

Everything works the code is working, I just wanted to know if there is a possibility of changing the value of the first installment, and the rest adjust automatically.

    
asked by anonymous 24.10.2017 / 20:52

1 answer

1

I created some functions to count the number of rows, the total amount to divide between the other rows, and other currency format treatments. I also changed the listener from keyup to keypress because it was bugging. Remember that the code below will only work by changing the first plot value:

$(document).ready(function() {
	valor_total = novas_parcelas_temp = 0;
	;
	$("#table_com_parcelas td[title=valor]").each(function(){
		valor_total += Number($(this).text().replace(/[^0-9\,-]+/g,"").replace(',','.'));
	});
	numero_tds = $("#table_com_parcelas td[title=valor]").length-1;
});



$(document).on('click', function() {
  $('#table_com_parcelas tbody tr').each(function(i) {
    $(this).children('td').each(function(p) {
      if (($(this).attr('title') === 'valor') || $(this).attr('title') === 'vencimento') {
        $(this).dblclick(function() { //inicio dblclick

          if ($('td > input').length > 0) {
            return;
          }

          var conteudoOriginal = $(this).text();
          var novoElemento = $('<input/>', {
            type: 'text',
            value: conteudoOriginal
            // blur: somaTds()

          });
          if ($(this).attr('title') === 'valor') {
            $(novoElemento).maskMoney({
              prefix: 'R$ ',
              allowNegative: true,
              thousands: '.',
              decimal: ',',
              affixesStay: true
            });
          }
          if ($(this).attr('title') === 'vencimento') {
            $(novoElemento).mask("99/99/9999");
          }

          $(this).html(novoElemento.bind('blur keypress', function(e) {

			if($(this).parent().attr('title') == 'valor'){

				if(e.type !== "blur"){
					novas_parcelas_temp = ((valor_total - Number($("#table_com_parcelas td[title=valor] input")
					.eq("0")
					.val()
					.replace(/[^0-9\,-]+/g,"")
					.replace(',','.')))/numero_tds)
					.toFixed(2)
					.replace('.','');
				}
	
				if(novas_parcelas_temp != 0){
					novas_parcelas = novas_parcelas_temp.toString().replace(/([0-9]{2})$/g, ",$1");
					if( novas_parcelas.length > 6 ){
						novas_parcelas = novas_parcelas.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
					}
		
					$("#table_com_parcelas td[title=valor]:not(:eq(0))").each(function(){
						$(this).text('R$ '+novas_parcelas);
					});
				}
			}
			
            var keyCode = e.which;
            var conteudoNovo = $(this).val();
            if (keyCode == 13 || keyCode == 9 || keyCode == 0 && conteudoNovo != '' && conteudoNovo != conteudoOriginal) {
              var objeto = $(this);
              $.ajax({
                type: "POST",
                url: "#",
                data: {
                  id: $(this).parents('tr').children().first().text(),
                  campo: $(this).parent().attr('title'),
                  valor: conteudoNovo
                },
                success: function(result) {
                  objeto.parent().html(conteudoNovo);
                  $('#valor_total').text(result);
                }
              });
              var posicao = p + 1;
              if(p == 2){              
              $(this).parent()
                .html(conteudoNovo)
                .parents('tr')
                .next()
                .children('td:nth-child(' + posicao + ')')
                }else{
                $(this).parent()
                .html(conteudoNovo)
                .parents('tr')
                .next()
                .children('td:nth-child(' + posicao + ')')
                .trigger('dblclick');
                }

            } else if (keyCode == 27 || e.type == 'blur')
              $(this).parent().html(conteudoOriginal);
          }));
          $(this).children().select();
        } /*fim dblclick*/ );
      };
    });
  });
});
<script src="https://code.jquery.com/jquery-3.2.1.js"integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<table id="table_com_parcelas" class="table table-condensed">
  <thead>
    <tr>
      <th class="align">Parcela</th>
      <th class="align">Vencimento</th>
      <th class="align">Valor</th>
      <th class="align">Forma pagamento</th>
    </tr>
  </thead>
  <tbody>
    <tr id="row-1">
      <td class="align">1 de 3</td>
      <td title="vencimento" class="align">24/10/2017</td>
      <td title="valor" class="align">R$ 10.000,00</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-1" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-1" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-1"></span>
          </form>
        </div>
      </td>
    </tr>
    <tr id="row-2">
      <td class="align">2 de 3</td>
      <td title="vencimento" class="align">24/11/2017</td>
      <td title="valor" class="align">R$ 10.000,00</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-2" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-2" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-2"></span>
          </form>
        </div>
      </td>
    </tr>
    <tr id="row-3">
      <td class="align">3 de 3</td>
      <td title="vencimento" class="align">24/12/2017</td>
      <td title="valor" class="align">R$ 10.000,00</td>
      <td title="form" class="align form">
        <div class="form-inline">
          <form id="formulario-3" action="" method="post" data-toggle="validator" role="form"><select name="forma" class="form-control" id="select-3" required=""><option value="">Selecione</option><option value="1">Boleto</option><option value="2">Cartão</option><option value="3">Cheque</option><option value="4">Dinheiro</option><option value="5">Transferência</option></select>
            <span class="form-full-3"></span>
          </form>
        </div>
      </td>
    </tr>
  </tbody>
</table>
    
24.10.2017 / 22:32