html - I'm Having trouble with Javascript. It says that "TypeError: document.forms.inputs is undefined" -


i'm struggling work, , couldn't other valuable resources. guess main problem referencing of variables in dom format. have code right here(i'm not sharing css may not important in error)

`

<script> var a, b, c; = document.forms["inputs"]["deg_2"].value; b = document.forms["inputs"]["deg_1"].value; c = document.forms["inputs"]["deg_0"].value;   var d = b^2 - 4*a*c;    var ans1 = (-b + sqrt(d)/2*a);   var ans2 = (-b - sqrt(d)/2*a);   function result(){      document.getelementbyid('answer1').innerhtml = ans1;     document.getelementbyid('answer2').innerhtml = ans2; } </script> </head> <body>   <div class = "head"> <h1 class = "head">  quad root finder </h1>   </div>   <div class = "message"> <h3 class = "message">  hello user, making quad root finder 1 of starting project. </h3>   </div> <div class = "derivative"> <form name = "inputs">     <input type="text" name = "deg_2" ></input><lable = "x^2"> x^2 +  </lable>     <input type = "text" name = "deg_1"></input><lable = "x"> x +  </lable>     <input type = "text" name = "deg_0"></input><lable = "constant"> </lable><br><br>     <button onclick="result()"> find roots </button> </form> </div> <p class = "answer_title"> answer: </p> <div class = "answer">     <h3 id = "answer1"> </h3>     <h3 id = "answer2"> </h3> </div> </body> 

`

the reason you're getting error because javascript code @ top of html page. means gets executed before html gets parsed. therefore, when code gets run, elements don't exist far browser's dom concerned.

as pointed out in comments of question, should move of logic within result function otherwise ans1 , ans2 ever have original value when page loads.

as practice, should move javascript bottom of html in order allow dom loaded before executes.

<body>     // other html     <script>         function result(){             var a, b, c;             = document.forms["inputs"]["deg_2"].value;             b = document.forms["inputs"]["deg_1"].value;             c = document.forms["inputs"]["deg_0"].value;             var d = b^2 - 4*a*c;              var ans1 = (-b + sqrt(d)/2*a);             var ans2 = (-b - sqrt(d)/2*a);             document.getelementbyid('answer1').innerhtml = ans1;             document.getelementbyid('answer2').innerhtml = ans2;         }     </script> </body> 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -