javascript - Why do I get a type error when trying to access the value of an element stored in a variable? -
i’m having trouble storing input element in javascript variable. please see code below. commented out bits not work. code works is; however, not dry. overly verbose. storing element in variable clean things up, when attempt (and push value x
array) “uncaught type error: cannot read property value
of null
”.
please see markup , script attached. why error when use variable form of document.getelementbyid
, not when hardcode element on , 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) , 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>
paul roub left comment fixed it. loading script in head of html document rest of source files. problematic because elements referenced js not created on dom yet. when moved script end of html document, store element in variable.
Comments
Post a Comment