0

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?

4
  • 1
    It's because you're adding the value for every character that's typed. Eg. if you type 10, it adds 0 + 1 for the first character, then 1 + 10. Commented Oct 24, 2019 at 9:53
  • then what will be correct solution for this ? @RoryMcCrossan Commented Oct 24, 2019 at 9:54
  • 1
    Try the change event instead Commented Oct 24, 2019 at 9:55
  • try my answer with the change event. @MohammedSabir Commented Oct 24, 2019 at 10:11

5 Answers 5

3

On your code when you enter the first digit it's been calculated to the total because of your code total += parseInt($(this).val()). for example, if your press first digit as 1 then at that time total is updating as total = total + 1 which equals 1, on the second keypress, for example, take 0, then your input value becomes 10. it is calculating to the current total value as total = total + 10. that's why you are getting 11 as answer

Try like this.

$(document).ready(function(){
$(".test").on("input", function(){
    let total = 0;
    $('.test').each(function() {
      if (!isNaN(parseInt($(this).val()))) {
        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="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>

Sign up to request clarification or add additional context in comments.

5 Comments

Please explain why you think this is the solution instead of just some code, so that OP can understand and solve it themself next time :)
You can't just hardcoded the input select method suppose if there are more than two input fields then your code condition will be going to modified again and again. Try my answer as well or you can update your answer. @Yahiya
you are right @ShubhamBaranwal. But on his question, he said he has two text fields, no mention of the dynamic amount of fields that why I added the answer like this. Also, a thumbs up for your answer too... ;)
True, but your answer does not only help this user, but your answer can also help others too if it's optimized and scalable for others. @Yahiya
@ShubhamBaranwal acknowledged
1

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/

Comments

1

You just update total with that input value that you're trying to change.

For getting the total for both input values you have to take both values and add it with the total.

Try below code-

$(document).ready(function() {
  $(".test").on("change", function() {
    var total = 0;
    $('.test').each(function() {
      if (!isNaN(parseInt($(this).val()))) {
        total += parseInt($(this).val());
      }
    });
    // Print entered value in a div box

    $("#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>

Comments

0
 $(document).ready(function () {
        $(".test").on('input', function () {
            var total = parseInt($("#result").text());
            total = parseInt($("#myInput").val()) + parseInt($("#myInput1").val());
            $("#result").text(total);
        });
    });

 <p><input type="text" class="test" placeholder="Type something..." id="myInput" /></p>
    <p><input type="text" class="test" placeholder="Type something..." id="myInput1" /></p>
    <div id="result"></div>

Comments

-1

Use the change event instead of the input event. It will only fire when the value is "commited", instead of every keystroke. See mdn for details.

1 Comment

You should write this into comment section, not as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.