I do an autosum of fields, but it does not show the value in textbox

1

What can be wrong in my function?

$(function() {
  $('#sumAll').Keydown(function() {
    var add = 0;
    $('.cl').each(function() {
      add += Number($(this).val());
    });
    $('#sumAll').text(+ add);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<head>
  <title>Sum TextBox values</title>
</head>
<body>
  <input id="Text1" class="cl" type="text" /><br />
  <input id="Text2" class="cl" type="text" /><br />
  <input id="Text3" class="cl" type="text" /><br />  
  <input id="sumAll" type="text" value="" /><br />
</body>
</html>
</body>
</html>
    
asked by Hlvr 03.11.2016 в 15:17
source

1 answer

2

I do not understand why you occupy the event keydown , when this what it does is that if the user writes in an input there is just called the event. I would recommend that if you want to do an "autosuma" play with the event onChange

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
  function suma() {
      var add = 0;
      $('.cl').each(function() {
          if (!isNaN($(this).val())) {
              add += Number($(this).val());
          }
      });
      $('#sumAll').val(add);
  };
  </script>
</head>

<body>
  <input id="Text1" class="cl" type="text" onChange="suma();" />
  <br />
  <input id="Text2" class="cl" type="text" onChange="suma();" />
  <br />
  <input id="Text3" class="cl" type="text" onChange="suma();" />
  <br />
  <input id="sumAll" type="text" value="" />
  <br />
</body>

</html>

This is what you do while changing the values of your inputs, adding them but verifying that the content of each one is a number.

    
answered by 03.11.2016 / 15:41
source