I'm trying to get the innerHTML function in Javascript to work -
i want heating answer appear next heating surface (mm) can't make work. following error message chrome console
uncaught typeerror: cannot read property 'value' of null
i know else works because added alert box, need innerhtml work though.
here html:
<html> <head> <script type="text/javascript" src="pipeheaterfunction.js"> </script> </head> <body> <table> <tr><td>inner diameter (mm):</td> <td><input id="dia" onkeypress="pipeheater();"></td> <tr><td>pipe thickness (mm):</td> <td><input id="thi" onkeypress="pipeheater();"></td> <tr><th>calculate heater:</th> <td><button onclick="pipeheater();">calculate</button></td></tr> <tr><td>heating surface(mm):</td> <td><span class="output" id="surface"></span></td></tr> </table> </body> </html>
here javascript code:
function pipeheater(){ //dia inner diameter of pipe, thi pipe thickness var dia = document.getelementbyid("dia").value; var thi = document.getelementbyid("thi").value; var hsur; //hsur heating surface required pipe in mm hsur = 5*math.sqrt(((dia-thi)*thi)/2); var surface = hsur; if(surface>0){ surface.innerhtml=surface.tofixed(1); alert(surface.tofixed(1)); } } window.onload=pipeheater();
there 2 errors in script. @ first, when setting
window.onload = pipeheater();
pipeheater
invoked immediately, it's not waiting window.onload
fired, , error when trying read value of yet-non-existing element. can fix this:
window.onload = pipeheater;
secondly, try use innerhtml
of hsur
, number. need define variable actual html element. below fixed code.
function pipeheater() { var dia = document.getelementbyid("dia").value, thi = document.getelementbyid("thi").value, hsur = 5 * math.sqrt(((dia - thi) * thi) / 2), surface = document.getelementbyid("surface"); if (hsur > 0) { surface.innerhtml = hsur.tofixed(1); alert(hsur.tofixed(1)); } } window.onload = pipeheater;
you can check how works @ jsfiddle. i'd recommend validate values of dia
, thi
before making calculations them. using onchange
instead of onkeypress
might more comfortable users, , give more reliable results.
Comments
Post a Comment