Uncaught TypeError: Cannot read properties of null (reading 'value') getElementById

95 views Asked by At

I'm getting this error when clicking on the button.

Uncaught TypeError: Cannot read properties of null (reading 'value')

What am I doing wrong? Here's the code:

 <table>
                <tr>
                    <th>Height (inches)</th>
                    <th>Width (inches)</th>
                    <th>Length (inches)</th>
                    <th>Pieces</th>
                    <th>Bd Ft</th>
                    <th>Lineal Ft</th>
                    <th>Sqare Ft</th>
                </tr>
                <tr>
                    <td>
                        <input type="text" value="1" id="height" /></td>
                    <td>
                        <input type="text" value="1" id="width" /></td>
                    <td>
                        <input type="text" value="1" id="length" /></td>
                    <td>
                        <input type="text" value="1" id="pieces" /></td>
                    <td>
                        <input type="text" value="" id="bdft" /></td>
                    <td>
                        <input type="text" value="" id="linealft" /></td>
                    <td>
                        <input type="text" value="" id="sqft" /></td>
                </tr>
            </table>
            <input type="button" value="Calculate" onclick="calculate()" />
            <script type="text/javascript">
                function calculate() {
                   
                    var heightVar = document.getElementById(height);
                    var widthVar = document.getElementById(width);
                    var lengthVar = document.getElementById(length);
                    var piecesVar = document.getElementById(pieces);

                    alert(document.getElementById(height).value);
                  
                }

            </script>

What am I doing wrong? I would expect to get 'height' value in an alert window.

2

There are 2 answers

0
surfdmountain On

I was missing quotations.

var heightVar = document.getElementById(height);

Needed to be

var heightVar = document.getElementById("height");
0
normalcepalin On

Looks like you need to wrap your id values in quotes, since they are all strings

var heightVar = document.getElementById("height");
var widthVar = document.getElementById("width");
var lengthVar = document.getElementById("length");
var piecesVar = document.getElementById("pieces");