javascript - Trying to understand JS functions - what am I doing wrong? -


i'm working way through beginner's javascript course on treehouse , keep getting stuck on functions. in effort understand better, tried creating calculator converts human years dog years. here code far:

html:

<div id="calculator">   <form>     <label>what current age in human years? <br>     <input type="text" id="humanyears"></label> <br>     <button type="text" id="calculate">calculate</button>   </form> </div> 

js:

function calculate() {  var humanyears = document.getelementbyid("humanyears").value;  var dogyears = (humanyears * 7);  document.write(dogyears); }  document.getelementbyid("calculate").onclick = function(){calculate(); }; 

the page flickers , keep seeing form, no result.

i know code incorrect don't understand why. know can copy other people's code github , have functioning calculator kind of defeats purpose of learning. rather know why code doesn't work , can fix it. (i double, triple checked html , js files linked, are.)

any js wizards out there care chime in?

edit: when enter age form, merely reloads, rather displaying age in dog years (which desired outcome).

here working code little changes possible:

<div id="calculator">   <form>     <label>what current age in human years? <br>     <input type="text" id="humanyears"></label> <br>     <button type="text" id="calculate">calculate</button>   </form> </div>  <script>   function calculate() {     var humanyears = document.getelementbyid("humanyears").value;     var dogyears = (humanyears * 7);     document.write(dogyears);   }    document.getelementbyid("calculate").onclick = function(){calculate(); return false; }; </script> 
  • assuming put in 1 file script tags missing. if not still need script tag load js file.
  • your function needed "return false;". if omit that, page reload after writing output , won't see output. happens because default behaviour of button in form reload page. returning "false" suppress that.

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -