Adding values between html and javascript inputs

Asked

Viewed 4,753 times

5

Dear friends, I am trying to add sum between html and javascript inputs, but with this example, I was only able to put in the html input. How do I implement the javascript input and add the value together with the Total Value?

inserir a descrição da imagem aqui

In Html this is how:

html

<script type="text/javascript">
  function calcular(){
      var valor1 = parseInt(document.getElementById('txt1').value);
      var valor2 = parseInt(document.getElementById('txt2').value);
      document.getElementById('result').value = valor1 + valor2;
  }
<div class="form-group col-md-3">
    <label for="titulo">Valor:</label>
        <input type="text" class="form-control" value="0" id="txt1" name="responsavel" onfocus="calcular()" >
</div>

<div class="form-group col-md-3">
    <label for="titulo">Valor Total:</label>
        <input type="text" class="form-control" name="responsavel" id="result" readonly>
</div>

In the javascript where I add other dependents this way:

javascript

AddTableRow = function() {

    var newRow = $("<tr>");
    var cols = "";

    
    cols += '<td><input type="text" name="usuarios['+ currentRow + '][nome]"></td>';

    cols += '<td><input type="text" name="usuarios['+ currentRow + '][cpf]"></td>';

    cols += '<td><select name="usuarios['+currentRow +'][cargo]">';
    cols += '<option value="gerente" name="usuarios['+currentRow +'][gerente]">Gerente</option>';
    cols += '<option value="Professor" name="usuarios['+currentRow +'][Professor]">Professor</option>';
    cols += '<option value="Programador" name="usuarios['+currentRow +'][Programador]">Programador</option>';
    cols += '</select></td>';

    cols += '<td><input type="text" name="usuarios['+currentRow +'][email]"></td>';

    cols += '<td><input type="text" name="usuarios['+currentRow +'][parentesco]"></td>';

    cols += '<td><input type="text" id="txt2 onblur="calcular()" name="usuarios['+currentRow +'][valor]"></td>';

    cols += '<td class="actions">';
    cols += '<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>';
    cols += '</td>';

    newRow.append(cols);

    $("#products-table").append(newRow);

    currentRow++;

    return false;
};
  • 1

    Can you adapt jsFiddle to your code with the remaining problem? https://jsfiddle.net/L4sy0gk8/

  • Check out @Sergio https://jsfiddle.net/9zv3k4m3/2/# - When I add more dependents, the value does not add up

2 answers

4

The first thing to do is arrange your function to add rows in the table.

When observing the line below, we can observe that you forgot the quotation marks when placing the ID of input. With that, the onblur() doesn’t work.

cols += '<td><input type="text" id="txt2 onblur="calcular()"name="usuarios['+currentRow +'][valor]"></td>';

Change to Iss: o id="txt2" onblur="calcular()"

cols += '<td><input type="text" id="txt2" onblur="calcular()" name="usuarios['+currentRow +'][valor]"></td>';

After that, just change your function calcular() to get the values of all inputs, and not just the txt1 and txt2. I’m calculating the values by class because I think it’s simpler.

 function calcular() {
      var total = 0;
      var x = document.getElementsByClassName("valor");
      for (var i = 0; i < x.length; i++) {
        total +=  parseFloat(x[i].value);
      }
      document.getElementById("result").value = total;
    }

Once done, your sum should work according to the example below:

var currentRow = 0;
var AddTableRow = function() {
  var newRow = $("<tr>");
  var cols = "";
  cols += '<td><input type="text" name="usuarios[' + currentRow + '][nome]"></td>';
  cols += '<td><input type="text" name="usuarios[' + currentRow + '][cpf]"></td>';
  cols += '<td><select name="usuarios[' + currentRow + '][cargo]">';
  cols += '<option value="gerente" name="usuarios[' + currentRow + '][gerente]">Gerente</option>';
  cols += '<option value="Professor" name="usuarios[' + currentRow + '][Professor]">Professor</option>';
  cols += '<option value="Programador" name="usuarios[' + currentRow + '][Programador]">Programador</option>';
  cols += '</select></td>';
  cols += '<td><input type="text" name="usuarios[' + currentRow + '][email]"></td>';
  cols += '<td><input type="text" name="usuarios[' + currentRow + '][parentesco]"></td>';
  cols += '<td><input type="text" id="txt2" onblur="calcular()" name="usuarios[' + currentRow + '][valor]" class="valor"></td>';
  cols += '<td class="actions">';
  cols += '<button class="btn btn-large btn-danger" onclick="$(this).parent().parent().remove()" type="button">Remover</button>';
  cols += '</td>';
  newRow.append(cols);
  $("#products-table").append(newRow);
  currentRow++;
  return false;
};



function calcular() {
  var total = 0;
  var x = document.getElementsByClassName("valor");
  for (var i = 0; i < x.length; i++) {
    total +=  parseFloat(x[i].value);
  }
  document.getElementById("result").value = total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group col-md-3">
  <label for="titulo">Valor Total:</label>
  <input type="text" class="form-control" name="responsavel" id="result" readonly>
</div>


<br/>

<table id="products-table">
  <tr>
    <td>Nome</td>
    <td>CPF</td>
    <td>Cargo</td>
    <td>E-Mail</td>
    <td>Parentesco</td>
    <td>Valor</td>
    <td>Ações</td>
  </tr>
</table>

<br/>

<button onclick="AddTableRow()">
  Adicionar Dependentes
</button>

Since you are using jQuery, you can change its function to this, if you find it simpler:

 function calcular() {
         $('.valor').each(function() {
            total += parseFloat($(this).val());
          });
          $('#result').val(total);
    }

3


You can simplify that and clone each tr:

 var AddTableRow = function(el) {
     var tbody = $(el).closest('table').find('tbody'); // ir buscar o tbody
     var row = tbody.find('tr:last').clone(); // criar um clone
     var name = row.find('.calcular').attr('name'); // buscar o nome do clone
     var index = parseInt(name.match(/usuarios\[(\d+)\]\[valor\]/)[1], 10) + 1; // ler o numero (que é do original ainda)
     row.find('.calcular').attr('name', 'usuarios[' + index + '][valor]'); // dar novo numero ao clone
     tbody.append(row); // adicionar no HTML
 };

and grouping these inputs in HTML with a class could look like this:

function calcular() {
    var soma = $('.calcular').get().reduce(function(soma, el) {
        return (parseInt(el.value, 10) || 0) + soma;
    }, 0);
    document.getElementById('result').value = soma;
}

jsFiddle: https://jsfiddle.net/1fz9rx41/

Note: I joined thead and tbody to your HTML that had missing tags.

  • 2

    The person does not know how to play and responds with two little blocks of code... This is theft :p. +1 for simplicity

  • @Randrade is simpler than writing all that HTML via Javascript :P

  • 2

    I agree. In addition to being simpler, it avoids typos, such as the lack of quotation marks in the ID.

Browser other questions tagged

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