Thursday, May 23, 2024
12
rated 0 times [  17] [ 5]  / answers: 1 / hits: 184709  / 15 Years ago, wed, december 2, 2009, 12:00:00

Why does refButton get null in the following JavaScript code?



<html>
<head>
<title></title>
<script type=text/javascript>
var refButton = document.getElementById(btnButton);

refButton.onclick = function() {
alert('I am clicked!');
};
</script>
</head>
<body>
<form id=form1>
<div>
<input id=btnButton type=button value=Click me/>
</div>
</form>
</body>
</html>

More From » getelementbyid

 Answers
27

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:



<html>
<head>
<title></title>
<script type=text/javascript>
window.onload = function(){
var refButton = document.getElementById(btnButton);

refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id=form1>
<div>
<input id=btnButton type=button value=Click me/>
</div>
</form>
</body>
</html>

[#98179] Friday, November 27, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ciarajourneyv

Total Points: 428
Total Questions: 95
Total Answers: 90

Location: Maldives
Member since Sat, Feb 11, 2023
1 Year ago
;