2

I have this HTML and Java Script. I am setting to display the Total amount of these 3 input field automatically. But it gaves me wrong answer if I use + (adding). I works well if I use * (multiply) or / (devide.) Any one please Help!

Here's my HTML code.

</pre>
    <tr>
        <td><input type='number' id='amt1' name='amt1' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='amt2' name='amt2' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='amt3' name='amt3' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='total' name='total' class='form-control' readonly='readonly'></td>
    </tr>
<pre>

Heres my Java Script...

<script type="text/javascript">

    function total_amount()
    {
        document.getElementById('total').value = document.getElementById('amt1').value + document.getElementById('amt2').value + document.getElementById('amt3').value
    }

    function numbersonly(e){
       var unicode=e.charCode? e.charCode : e.keyCode
       if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=27 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow)
           if (unicode<48||unicode>57)
               return false
        }
    }

</script>
</pre>
2
  • Why does "1" + "1" == "11"? Oh, you're adding strings… Commented Oct 2, 2014 at 6:14
  • 1
    Limiting user input to certain keys is not user friendly, and doesn't stop entry of non–digits via pasting or other means, just don't do it. You only care what the value is after the user has finished inputting it, how they got there is up to them. Commented Oct 2, 2014 at 6:25

5 Answers 5

2

Keep it simple. Use event delegation and one keyUp handler. Don't use inline handlers. Convert the field value to Number before your do calculations with it. Here's an example:

document.querySelector('table').addEventListener('keyup', sum);

function sum(e) {
  var from = e.target || e.srcElement
     ,isNumericInput = /number/i.test(from.type);
  if (!isNumericInput) {return true;}
  var d = document
     ,inputs = d.querySelector('table').querySelectorAll('[type=number]')
     ,sumfld = d.querySelector('#sum')
     ,sumnow = 0;
  
  [].forEach.call(inputs,
                  function (v) {
                      sumnow += +(v.value); //<= conversion to Number, using +
                   });
  
  sumfld.textContent = sumnow;
}
<table>
  <tr>
   <td><input type='number' id='amt1' name='amt1' class='form-control'></td>
   <td><input type='number' id='amt2' name='amt2' class='form-control'></td>
   <td><input type='number' id='amt3' name='amt3' class='form-control'></td>
   <td><b>Total</b>: <span id="sum"></span></td>
  </tr>
</table>

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

5 Comments

where should i put these? document.querySelector('table').addEventListener('keyup', sum); these should be included in my script function?
@JohnArzaga at the top of your script, or within an onload handler
@RobG, sure. It's no showstopper I'd say, but removed the || 0 part.
something like <table onload='document.querySelector('table')> or <body onload= ??
@JohnArzaga 1. window.onload = function (){ document.querySelector('table').addEventListener('keyup', sum) }; 2. place the <script>...</script> tag right before the closing </body> tag and place the handler assignment as first line within the script.
1

use

document.getElementById('amt1').value|0 +
document.getElementById('amt2').value|0 +
document.getElementById('amt3').value|0 ;

OR

parseInt(document.getElementById('amt1').value) +
parseInt(document.getElementById('amt2').value) +
parseInt(document.getElementById('amt3').value) ;

so that these considered as number

5 Comments

Code only answers aren't liked, explain the OPs issue and why your answer fixes it. |0 is not a good strategy if the OP is using floats.
parseInt should be used. but it does not allow text box to be empty. you should enter 0.
then put check of empty text box. If textbox is empty, either use 0 or not parse the string.
i want my textbox to look clean. 0 should not appear if one of the amount is empty.
do not write 0 inside text box just use it for your calculation
1

change your function

function total_amount() {
    var amt1 = parseInt(document.getElementById('amt1').value);
    if (isNaN(amt1)) {
        amt1 = 0;
    }

    var amt2 = parseInt(document.getElementById('amt2').value);
    if (isNaN(amt2)) {
        amt2 = 0;
    }

    var amt3 = parseInt(document.getElementById('amt3').value);
    if (isNaN(amt3)) {
        amt3 = 0;
    }

    document.getElementById('total').value = amt1 + amt2 + amt3;
}

1 Comment

than don't forget to right mark. so it'll help others.
1

use parseInt().

function total_amount()
{
    document.getElementById('total').value =parseInt( document.getElementById('amt1').value) +   
parseInt(document.getElementById('amt2').value) + parseInt(document.getElementById('amt3').value)
}

Comments

1

A simple solution for converting a string (returned by .value) to a number is to use the unary + operator:

function total_amount() { 
    document.getElementById('total').value = 
        +document.getElementById('amt1').value + 
        +document.getElementById('amt2').value + 
        +document.getElementById('amt3').value 
} 

Comments

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.