0

Why does it always display "undefined" when I run this html?

This program is used for finding the grand common divisor. Could anyone tell me what is the problem with it? <!DOCTYPE HTML> <html> <head> <title>GCD</title> <script type="text/javascript"> function result(){ var a=document.getElementById("first"); var b=document.getElementById("second"); var o=Math.min(a,b); var j=Math.abs(o); var im=count(j); var c=document.getElementById("third"); c.innerHTML=im; } function count(j){ var il; for(var x=1;x<=j;++x){ var l=x; if(a%l==0&&b%l==0){ il=0; il+=l; } } return il; } </script> </head> <body> <p>First Number</p> <br/> <input type="number" id="first"/> <br/Second Number</p> <br/> <input type="number" id="second"/> <br/> <button onclick="result()"> OK </button> <br/> <p id="third"></p> </body> </html>

24th Dec 2016, 8:16 AM
Queven
Queven - avatar
2 odpowiedzi
+ 3
The explanation: You're JS script is in the <head> tag... so when the browser load page, the script is executed before the <body> was loaded: then the getElementById() function can't find them and return "undefined". So you must differ execution after page is fully loaded ( or minimal, the elements you need ). The NoName solution, is to avoid global variables and call getElementById() function inside custom function result(), which is necessarly executed when the page is loaded, because is called by another element on the page. If you want keep your global variables and set them, at start, once, you can move all your script at the end of the <body> tag content ( just before the </body> closing tag ): so when it run, the required elements are already loaded. Or encapsulate your initialization instructions ( setting their values, declaration of global variables must keep outside any function ) in a custom function, and call it when page is loaded. There are many solutions, among which: - put the call of your initalizator in the "onload" attribute of <body> tag ( <body onload="my_init_func();"> ) - put the call in a script placed at end of <body> tag content ( or minimal after required elements ): <script>my_init_func();</script> There are a lot of another solutions working too... The essential is to understand how an html page and is elements is handle by browsers ;)
24th Dec 2016, 10:52 AM
visph
visph - avatar
0
Got it. Thanks for your help!
24th Dec 2016, 12:36 PM
Queven
Queven - avatar