How to Generate Sum in looped fields [closed]

-1

As I am not aware of javascript I need a help how can I do, this script below perform the sum of the items in the "value" fields of each looped line

In case it would have to appear in the field "Total" dynamically the sum of each line

		(function ($) {
		  $('#destino_in').on('change', function () {
		      var $self = $(this);

		      $('#destino_out').val($self.val());
		  });
		}(jQuery));

		$(function () {
		  var divContent = $('#materialInst');
		  var botaoAdicionar = $('a[data-id="1"]');
		  var i = 1;
		  // VARIAVEL ADD
		  var destino;

		  //Ao clicar em adicionar ele cria uma linha com novos campos
		  $(botaoAdicionar).click(function () {

		    $('<div class="conteudoIndividual"><tr><td>'+
		      '<input type="text" name="estado" size="5" class="form-control" value="" />'+
		      '<select name="destino_in" id="destino_in" class="destino_in form-control">'+
		        '<option value="" selected disabled>Selecione...</option>'+
		        '<option value="Vilamar-10,00">Vilamar</option>'+
		        '<option value="Savoy-20,00">Savoy</option>'+
		      '</select>'+
		      '<input type="text" placeholder="Valor" name"valor" id="valor" class="form-control" />'+
		      '<input type="text" size="5" name="numero" class="form-control" value="" />'+
		      '<a href="#" class="linkRemover">Remover</a></td></tr></div>').appendTo(divContent);

		    $('#removehidden').remove();
		    i++;
		    $('<input type="hidden" name="quantidadeCampos" value="' + i + '" id="removehidden">').appendTo(divContent);

		    // ADD AQUI
		    // Aqui acontece a inserção dos valores no outro input
		    destino = $('.destino_in');

		    // verifico no evento de change
		    destino.on('change', function() {
		        // quando ocorrer, capturo o valor selecionado
		        var selected = $(this).val();
		        // divido a string em 2, separada pelo (-) [nome(-)valor]
		        var res = selected.split("-", 2);

		        // res[0] = "Vilamar";
		        // res[1] = "10,00";

		        // adiciono no input #valor o resultado do array na posição 1
		        $(this).next().val(res[1]);
		    });
		    // FIM ADD
		  });

		  //Cliquando em remover a linha é eliminada
		  $('#materialInst').on('click', '.linkRemover', function () {
		    $(this).parents('.conteudoIndividual').remove();
		    i--;
		  });
		});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#" id="adicionar" data-id="1">Adcionar nova Linha</a>
  
<form id="form1" name="form1" action="src/acao/cli.php" method="POST" enctype = "multipart/form-data" > 
<table>
  <div id="materialInst">
  </div>
  
  
  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="total" placeholder="Total">   <-- aqui devera aparecer o somatório 
 </form>
</table>
    
asked by anonymous 03.10.2018 / 04:47

1 answer

0

There are a few ways that this can be done, this is just one of them.

Creating an array of objects to save information for each line:

To do this, first use the 'i' variable to make each item in this list unique, making each of the created divs have a 'data-id':

        $('<div class="conteudoIndividual" data-id="' + i + '"><tr><td>'+
          '<input type="text" name="estado" size="5" class="form-control" value="" />'+
          '<select name="destino_in" id="destino_in" class="destino_in form-control">'+
            '<option value="" selected disabled>Selecione...</option>'+
            '<option value="Vilamar-10,00">Vilamar</option>'+
            '<option value="Savoy-20,00">Savoy</option>'+
          '</select>'+
          '<input type="text" placeholder="Valor" name"valor" id="valor" class="form-control" />'+
          '<input type="text" size="5" name="numero" class="form-control" value="" />'+
          '<a href="#" class="linkRemover">Remover</a></td></tr></div>').appendTo(divContent);

You will now need to create a variable containing a list of objects where the data for each of the lines will be stored:

  ...
  var divContent = $('#materialInst');
  var botaoAdicionar = $('a[data-id="1"]');
  var itens = [];
  var i = 1;
  ...

The next step is, when a line is added, a new item will also be added in the array:

  ...
  // ADD AQUI
  // Aqui acontece a inserção dos valores no outro input
  destino = $('.destino_in');
  itens.push({
     "destino": "", 
     "valor": 0.0
  });
  // verifico no evento de change

Now, in the 'change' event of the destination, change the data of the previously inserted rows:

destino.on('change', function() {
    // quando ocorrer, capturo o valor selecionado
    var selected = $(this).val();
    // divido a string em 2, separada pelo (-) [nome(-)valor]
    var res = selected.split("-", 2);

    // res[0] = "Vilamar";
    // res[1] = "10,00";
    var idx = parseInt($(this).closest('div.conteudoIndividual').attr( 'data-id' )) - 1;
    itens[idx]["destino"] = res[0];
    if(res[1]) {
        itens[idx]["valor"] = parseFloat(res[1].replace(',', '.'));
    }
    // adiciono no input #valor o resultado do array na posição 1
    $(this).next().val(res[1]);
});

Now let's take the event of removing the item:

//Cliquando em remover a linha é eliminada
$('#materialInst').on('click', '.linkRemover', function () {
  var elementToRemove = $(this).parents('.conteudoIndividual');
  var idx = parseInt(elementToRemove.attr( 'data-id' )) - 1;
  itens.splice(idx, 1);
  elementToRemove.remove();
  i--;
});

It is now necessary, when changing a value in the select or when a row is removed, set the sum of the "value" field of each of the items in the array, so you can use the reduce method:

$('inpút[name=total]').val(itens.reduce(function (prev, curr) { return prev + curr["valor"]; }, 0.0).toFixed(2).replace('.', ','));

the full Javascript (included in your) stays:

(function ($) {
  $('#destino_in').on('change', function () {
      var $self = $(this);
      $('#destino_out').val($self.val());
  });
}(jQuery));
$(function () {
  var divContent = $('#materialInst');
  var botaoAdicionar = $('a[data-id="1"]');
  var i = 1;
  var itens = [];
  // VARIAVEL ADD
  var destino;

  //Ao clicar em adicionar ele cria uma linha com novos campos
  $(botaoAdicionar).click(function () {
    $('<div class="conteudoIndividual" data-id="' + i + '"><tr><td>'+
      '<input type="text" name="estado" size="5" class="form-control" value="" />'+
      '<select name="destino_in" id="destino_in" class="destino_in form-control">'+
        '<option value="" selected disabled>Selecione...</option>'+
        '<option value="Vilamar-10,00">Vilamar</option>'+
        '<option value="Savoy-20,00">Savoy</option>'+
      '</select>'+
      '<input type="text" placeholder="Valor" name"valor" id="valor" class="form-control" />'+
      '<input type="text" size="5" name="numero" class="form-control" value="" />'+
      '<a href="#" class="linkRemover">Remover</a></td></tr></div>').appendTo(divContent);
    $('#removehidden').remove();            
    $('<input type="hidden" name="quantidadeCampos" value="' + i + '" id="removehidden">').appendTo(divContent);
    i++;
    // ADD AQUI
    // Aqui acontece a inserção dos valores no outro input
    destino = $('.destino_in');
    itens.push({
      "destino": "", 
      "valor": 0.0
    });
    // verifico no evento de change
    destino.on('change', function() {
      // quando ocorrer, capturo o valor selecionado
      var selected = $(this).val();
      // divido a string em 2, separada pelo (-) [nome(-)valor]
      var res = selected.split("-", 2);
      var idx = parseInt($(this).closest('div.conteudoIndividual').attr( 'data-id' )) - 1;
      itens[idx].destino = res[0];
      if(res[1]) {
          itens[idx].valor = parseFloat(res[1].replace(',', '.'));
      }
      $('input[name=total]').val(itens.reduce(function (prev, curr) { return prev + curr.valor; }, 0.0).toFixed(2).replace('.', ','));
      // adiciono no input #valor o resultado do array na posição 1
      $(this).next().val(res[1]);
    });
    // FIM ADD
  });

  //Cliquando em remover a linha é eliminada
  $('#materialInst').on('click', '.linkRemover', function () {
    var elementToRemove = $(this).parents('.conteudoIndividual');
    var idx = parseInt(elementToRemove.attr( 'data-id' )) - 1;
    itens.splice(idx, 1);
    elementToRemove.remove();
    i--;
    $('input[name=total]').val(itens.reduce(function (prev, curr) { return prev + curr.valor; }, 0.0).toFixed(2).replace('.', ','));
  });
});
    
03.10.2018 / 06:16