Adding values between html and javascript inputs

5

Dear friends, I'm trying to add sum between html and javascript inputs, but with this example, I've just been able to put in the html input. How do I implement in the javascript input and add the value along with the Total Value?

NoHtmllookslikethis:

html

<scripttype="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 like this:

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;
};
    
asked by anonymous 19.12.2016 / 16:14

2 answers

3

You can simplify this and clone every 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 in the HTML these inputs with a class might 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: link

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

    
19.12.2016 / 16:55
4

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

Looking at the line below, we can see that you've forgotten the quotes by putting ID for input . This means that onblur() does not work.

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

Change to iss: id="txt2" onblur="calcular()"

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

After that, just change your calcular() function to get the values of all inputs , not just txt1 and txt2 . I'm calculating the values for the class because I find it 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 this is done, your sum should work as shown 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><divclass="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>

As you are using jQuery, you can change your function for this if you find it simpler:

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