How to Generate Summation in loop fields

Asked

Viewed 71 times

-1

As I have no knowledge of javascript need a help how I can do, this my script below perform the sum of the items of the fields "value" of each row in loop

In the case the "Total" field would dynamically appear 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>
<a href="#" 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>

  • The <input> dynamically generated for the value has the id="valor" which is wrong as it will force several elements on the page to have the same id. The same applies to all ids you are using on the generated line.

1 answer

0


There are some ways this can be done, this is just one of them.

Creating an array of objects to save the information of each row:

To do this, first valos use the variable 'i' 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);

Now it will be necessary to create a variable containing a list of objects where the data of each line will be stored:

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

The next step is, when a row is added, a new item will also be added to 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 destination change event, 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 deal with the item removal event:

//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--;
});

Now it is necessary, when changing a value in select or when a row is removed, to set the sum of the "value" field of each of the items in the array, for this, you can use the method reduce:

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

the complete Javascript (included in your) is:

(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('.', ','));
  });
});
  • Hello Friend I tried to ride here but it didn’t work... could put the full code here for me...

  • follow it assembled https://jsfiddle.net/8y0t4x25/

  • 1

    Okay, in the last part of the answer I added the javascript I explained to your question, I tested it in jsfiddle and it worked: https://jsfiddle.net/8y0t4x25/10/

Browser other questions tagged

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