How can I avoid this error? It works, but I've always seen this error, here is the 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 the 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 is issuing an error on load:
Uncaught TypeError: Cannot set property 'onchange' of null formatter.js:50
Forma formatter.js:50
(anonymous function) profil:148
I did it to avoid to put twice onchange and onkeyup
The variable is not yet made, this is the cause of the error, but how do I avoid it? I tried even to add all variable and initialise them as nulls, but still getting the error!
}on the last line of the function, in both functions. Never do that. Several experienced programmers attempting to help you totally missed the presence of the closing}. This should be a pretty good indication that you've stumbled upon a coding style that is to be avoided.document.getElementById(price)- you have to make sure this element always exists, if it doesn't then you'll keep getting the nulls.