i making webpage that gets input text boxes (). page has 3 buttons perform different functions. these functions share many variables made of variables global. problem when input text text boxes , click button function runs global variables don't initialize function can't run properly. need variables initialize before function runs. have cut code down simple can still show problem. original code had 3 buttons , 3 functions why need use global variables.
<html> <head> <body> <form> <br><input type="text" class="boxleft" placeholder="type here..." id="age"/> <br> <input type="text" id="retireage" class="boxleft" placeholder="type here..." /> </form> <button id="test" onclick="calcnw()" >test</button> <script type="text/javascript"> //global variables var age = document.getelementbyid("age").value; var rage = document.getelementbyid("retireage").value; function calcnw() { var workingyears = rage - age; alert(workingyears); } </script> </body> </html> in example function not work because rage , age empty. there anyway global variables initialize before runs of functions?
well, bad design. if wish keep variables global, should evaluate value in form upon function click. what's happening javascript populating values immediately, probably, before dom has finished loading. also, when you're defining globals based on application state, it's best add window.onload handler. have fun developing. :)
perhaps, can this:
age = 0; rage 0; function calcnw() { getinput(); var workingyears = rage - age; alert(workingyears); } function getinput(){ age = document.getelementbyid("age").value; rage = document.getelementbyid("retireage").value; }
Comments
Post a Comment