In the following code:
function Transact() {
if(document.getElementById(\'itctobuy\').value!=\'\') {
itctobuy = parseInt(document.getElementById(
Uncaught TypeError: Cannot read property 'value' of null
That tells you that at least one of those elements doesn't exist as of when that code runs, so getElementById
returns null
, which you're trying to read the value
property from.
getElementById
will only return null
if no element with the given ID exists in the document as of when you call it. In general, the reasons for the element not existing fall into these categories:
getElementById
too earlyid
(e.g., a typo)name
instead of an id
In your case, since this is on button click, it's probably #2 or #3. You can see which ID it's unhappy about by looking at the line the error identifies, or using your browser's debugger to step through the code statement-by-statement.
Let's look at each category:
getElementById
too earlyOne common error is to have code calling getElementById
in a script
block that's before the element in the HTML, like this:
<script>
document.getElementById("foo").innerHTML = "bar";
</script>
<!-- ...and later... -->
<div id="foo"></div>
The element doesn't exist as of when that code runs.
Solutions:
script
to the end of the HTML, just before the closing </body.
taggetElementById
in a callback, such as on the DOMContentLoaded
event, or a button click , etc.Don't use window.onload
or <body onload="...">
unless you really want to wait to run the code until all external resources (including all images) have been loaded.
id
This is really common, using getElementById("ofo")
when the element is defined with id="foo"
.
Example:
<div id="foo"></div>
<script>
document.getElementById("ofo").innerHTML = "I'm foo"; // Error
</script>
Solution: Use the right ID. :-)
name
instead of an id
getElementById("foo")
looks for an element with id="foo"
, not with name="foo"
. name
!= id
.
Example:
<input name="foo" type="text">
<script>
document.getElementById("foo").value = "I'm foo"; // Error
</script>
Solution: Use id
, not name
. :-) (Or look up the element with document.querySelector('[name="foo"]')
.)
getElementById
looks in the document for the element. So if the element has been created, but has not been added to the document anywhere, it won't find it.
Example:
var div = document.createElement("div");
div.id = "foo";
console.log(document.getElementById("foo")); // null
It doesn't look throughout memory, it just looks in the document (and specifically, the document you call it on; different frames have different documents, for instance).
Solution: Make sure the element is in the document; perhaps you forgot to append it after creating it? (But in the example above, you already have a reference to it, so you don't need getElementById
at all.)