Search code examples
javascriptjqueryinputhtml-input

How to Detect Change in a Text Input Box in jQuery


I have two text input text box and I want to do the total of whatever no entered by the user. Below is my code:

$(document).ready(function(){
    var total = 0;
    $(".test").on("input", function(){
        // Print entered value in a div box
        total += parseInt($(this).val());
        $("#result").text(	total);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
    <div id="result"></div>

When I input 10 first then it takes 11, then if I enter 100 then it takes 111, I am no getting why this happening. Where I am making an error, guide me?


Solution

  • The reason it didn't showed you the result you want to, is because the calculation is wrong. You now add the number to the total, every time one input field changes. So if you type 123, it takes 0 + 1 , then 1 + 12, then 13 + 123 so you'll have 136 as result.

    I wrote a possible solution for your question. The code is in the fiddle below.

    You could add a function where you calculate the total of all input fields (may be more than 2, it's generic).

    function calculateTotal(){
      var total = 0;
        $(".test").each(function( index ) {
          var value = $(this).val();
          if(value == ""){
            return;
          }
          total += parseInt(value);
    
        });
      $("#result").text(total);
    }
    

    And on the change of your input fields, you just execute that function.

    $(document).ready(function(){
        $(".test").on("input", function(){
            calculateTotal();
        });
    });
    

    Your example is in this fiddle: https://jsfiddle.net/xL6hgder/2/