javascript - How to avoid TypeError: Cannot set property 'onchange' of null -
how can avoid error? works, i've seen error, here code:
function separe(price) { nstr = number(document.getelementbyid(price).value) * 100 nstr += ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(nstr)) { nstr = nstr.replace(rgx, '$1' + ' ' + '$2'); } return nstr + " centimes" } function forma(price, dest) { var handler = function(e) { document.getelementbyid(dest).innerhtml = separe(price) }; document.getelementbyid(price).onchange = handler; //line 50 document.getelementbyid(price).onkeyup = handler; }
and html:
<input id="prix" type="number" name="prix" min="1" step="1"> <script> forma("prix", "hhh"); //profil 148 </script> <h1 id="hhh" > </h1>
my page issuing error on load:
uncaught typeerror: cannot set property 'onchange' of null formatter.js:50 forma formatter.js:50 (anonymous function) profil:148
i did avoid put twice onchange
, onkeyup
the variable not yet made, cause of error, how avoid it? tried add variable , initialise them nulls, still getting error!
the way can avoid error entirely having element you're asking ready in dom when query it.
assume have html:
<span id="monkey">hey i'm monkey</span> result hopeful monkey:<span id="result"></span> result not hopeful monkey:<span id="noresult"></span>
and javascript:
var hopefulmonkey = document.getelementbyid("monkey"); document.getelementbyid("result").innerhtml = hopefulmonkey; var notsohopefulmonkey = document.getelementbyid("nomonkeys"); document.getelementbyid("noresult").innerhtml = " "+notsohopefulmonkey;
the output be:
hey i'm monkey result hopeful monkey:[object htmlspanelement] result not hopeful monkey: null
you're therefore trying access element doesn't exist yet or @ if you're getting error.
that said, have else that's causing trouble since code you've posted works in chrome. version running?
i made fiddle of problem: http://jsfiddle.net/eqtqz/
i made fiddle demonstrating answer well: http://jsfiddle.net/vb2jp/1/ (it has monkeys it's fun too!)