-1

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.

Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?

JavaScript:

var x = [];
var y = [];

//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");

//var dataBox = document.getElementById("display");

function insert() {
    x.push(document.getElementById("xInput").value);
    y.push(document.getElementById("yInput").value);
    clearAndShow();
}

function clearAndShow() {
    //Clear fields
    xInput.value = "";
    yInput.value = "";

    //Show output
    document.getElementById("display").innerHTML = "";
    document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
    document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}

HTML:

<body>
    <div class="container">
        <form>
            <h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
            <input id="xInput" type="number" placeholder="x (delay)" />
            <input id="yInput" type="number" placeholder="y (value)" />
            <input type="button" value="save/show" onclick="insert()" />
        </form>
        <div id="display"></div>
    </div>
</body>
Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
  • Seems to work fine here http://jsfiddle.net/j08691/h5u6b5dg/ – j08691 Nov 14 '14 at 15:12
  • 1
    Where/when is this script run? If it's in (or loaded from) ``, those elements don't exist yet (when the commented lines are run). When the `insert()` function itself runs, they do. – Paul Roub Nov 14 '14 at 15:13
  • Paul Roub, Thanks! That was it. I was loading the script in the header before the elements existed! Wow. I spent hours trying to figure that out. Great lesson. – Travis Jones Nov 14 '14 at 15:17
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Dec 14 '15 at 07:46

1 Answers1

1

Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61