I’ve tried looking on stackoverflow, but can’t quite find the same issue as me – I’m certain the issue is easy to solve, but somehow…it’s not working.
I have some inputs, which will add/multiply/subtract/divide etc, in a calculator format.
What I want, is to remove unnecessary references to getElementById by declaring the variables outside of my function block (I don’t want any fancy multiple-getElementById assignments).
My Javascript is below:
//Declarations: designed to minimze calls to document.getElementByID
var number1 = document.getElementById("num1");
var number2 = document.getElementById("num2");
var numAnswer = document.getElementById("answer");
//Add together two numbers
function add()
{
numAnswer.value = parseFloat(number1.value) + parseFloat(number2.value);
}
It’s driving me insane – if I take out the variables and just use plain old document.getElementById, everything works. This should be so easy, but it’s just not working. I’ve checked spelling, and it all seems okay – is there something I’m missing?
This will work provided the script you show in your question appears after the elements in your page source. Otherwise the browser hasn’t parsed those elements yet so it can’t find them by ID.
The other way to get it to work is to do the assignments in an
onloador document-ready handler, because by the timeonloador document-ready occurs all elements are accessible no matter where they are in the page source.