Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById('id') is null javascript error

For some reason I get an document.getElementById('id') is null JS error on line 7 with the following markup and script:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
document.getElementById('calculate').onclick = function calculateQuad()
{
    var inputa = document.getElementById('variablea').value;
    var inputb = document.getElementById('variableb').value;
    var inputc = document.getElementById('variablec').value;

    root = Math.pow(inputb,2) - 4 * inputa * inputc;
    root1 = (-inputb + Math.sqrt(root))/2*inputa
    root2 = (-inputb + Math.sqrt(root))/2*inputa 

    document.getElementById('root1').value = root1;
    document.getElementById('root2').value = root2;
    if(root<'0')
    {
        alert('This equation has no real solution.')
    }
    else {
        if(root=='0')
        {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = 'No Second Answer'
        }
        else {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = root1
            }
        }
};
document.getElementById('erase').onlick = this.form.reset();
</script>
<style>
#container
{
    text-align: center;
}
</style>
</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    a:<input id="variablea" value="" type="text">
    <br/>
    b:<input id="variableb" value="" type="text">
    <br />
    c:<input id="variablec" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

What's the real problem here?

like image 960
Qcom Avatar asked Jun 16 '26 18:06

Qcom


2 Answers

It is indeed null. Your element doesn't exist on the page yet.

Either:

  • Move your <script> block below your code
  • Add a window.onload event.
like image 155
Jason McCreary Avatar answered Jun 19 '26 09:06

Jason McCreary


Alternatively: window.onload = function(){} works as well

like image 43
Azmisov Avatar answered Jun 19 '26 07:06

Azmisov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!