Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Add two textbox values and display the sum in a third textbox automatically

I have assigned a task to add two textbox values.I want the result of addition to appear in the 3rd textbox,as soon as enter the values in the first two textboxes,without pressing any buttons.

For eg:In the first textbox i want to enter 450,when i press digit 4 of number '450',then it will be added to the 3rd textbox,any number i press in the first two textboxes,suddenly that changes will be reflected on the third textbox.How can i do this?

Here i write my code call sum() in onkeyup

onkeyup="sum()"
function sum() {
        var txtFirstNumberValue = document.getElementById('txt1').value;
        var txtSecondNumberValue = document.getElementById('txt2').value;
        var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
        if(!isNaN(result)){
            document.getElementById('txt3').value = result;
        }
}

This is not working in chrome

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this

  function sum() {
       var txtFirstNumberValue = document.getElementById('txt1').value;
       var txtSecondNumberValue = document.getElementById('txt2').value;
       if (txtFirstNumberValue == "")
           txtFirstNumberValue = 0;
       if (txtSecondNumberValue == "")
           txtSecondNumberValue = 0;

       var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
       if (!isNaN(result)) {
           document.getElementById('txt3').value = result;
       }
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...