简体   繁体   中英

JavaScript keeps returning 0

<!DOCTYPE html>
 <html>
  <head>
    <meta charset="utf-8"/>
   </head>
 <body>
     <form id="window">
       <input type="text" id="num1"><br />
         <input type="text" id="num2"><br />
      <input type="button" value="Calculate" onClick="main()"><br />
 </form>
    <script>
      var num1 = Number(document.getElementById("num1").value);
        var num2 = Number(document.getElementById("num2").value);
       function main(){
         alert(num1 + num2);
        }
    </script>
  </body>
   </html>

This is my code tell me what I am doing wrong because whenever I call the alert() it just returns 0 to the screen. I have tried it in different browsers but with no luck. Go easy on me because I have started only about a week ago!``

It's because you're setting the values of num1 and num2 once , right at the beginning of the script when the inputs don't have anything in them yet ( Number("") is 0 ), not each time main is called. Just move those two lines into main so the values of the inputs as of the button click are used:

function main(){
    var num1 = Number(document.getElementById("num1").value);
    var num2 = Number(document.getElementById("num2").value);
    alert(num1 + num2);
}

You need to get num1 and num2 inside main() ; Use below code:

<!DOCTYPE html>
 <html>
  <head>
    <meta charset="utf-8"/>
   </head>
 <body>
     <form id="window">
       <input type="text" id="num1"><br />
         <input type="text" id="num2"><br />
      <input type="button" value="Calculate" onClick="main()"><br />
 </form>
    <script>
        function main(){
            var num1 = Number(document.getElementById("num1").value);
            var num2 = Number(document.getElementById("num2").value);
            alert(num1 + num2);
        }
    </script>
  </body>
   </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM