Sum of two textfields - javascript

前端 未结 3 981
日久生厌
日久生厌 2021-01-20 15:55

I found [this][1], rather difficult, javascript example online and I\'ve implemented it with success in my website.

However, I would like to get the result of, in th

相关标签:
3条回答
  • 2021-01-20 16:33

    Replace:

    document.getElementById('total').value = parseInt(sum);
    

    With:

    document.getElementById('total').value = sum;
    

    You have already done all the int-parsing you need to do.

    0 讨论(0)
  • 2021-01-20 16:40

    $("#value1, #value2").on('focusout', function() {
      var value2 = parseInt($("#value2").val()) > 0 ? parseInt($("#value2").val()) : 0;
      var value1 = parseInt($("#value1").val()) > 0 ? parseInt($("#value1").val()) : 0
      var sumOfValues = value1 + value2;
      console.log('Your sum is ' + sumOfValues);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" class="input" id="value1">
    <input type="text" class="input" id="value2">

    0 讨论(0)
  • 2021-01-20 16:54

    Well, if you have assigned ID's to text inputs, for example: <input type="text" id="my_input" />, then you can call it with document.getElementById('my_input').value.

    So:

    <input type="text" id="my_input1" />
    <input type="text" id="my_input2" />
    <input type="button" value="Add Them Together" onclick="doMath();" />
    
    <script type="text/javascript">
        function doMath()
        {
            // Capture the entered values of two input boxes
            var my_input1 = document.getElementById('my_input1').value;
            var my_input2 = document.getElementById('my_input2').value;
    
            // Add them together and display
            var sum = parseInt(my_input1) + parseInt(my_input2);
            document.write(sum);
        }
    </script>
    

    Naturally, that is a very basic script, it doesn't check to make sure the entered values are numbers. We have to convert the fields into integers, otherwise they'll be strings (so 2+2 would equal 22). When the button is clicked, the function is called, which makes a variable for each input box, converts them to ints, adds them, and outputs our sum.

    0 讨论(0)
提交回复
热议问题