Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  96] [ 2]  / answers: 1 / hits: 176222  / 12 Years ago, tue, january 8, 2013, 12:00:00

Im getting a error in the Web Inspector as shown below:



TypeError: 'null' is not an object (evaluating 'myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);

return false;

}')


Here is my Code (HTML):



<h2>Hello World!</h2>
<p id=myParagraph>This is an example website</p>

<script src=js/script.js type=text/javascript></script>

<form>
<input type=text id=myTextfield placeholder=Type your name />
<input type=submit id=myButton value=Go />
</form>


Here is the JS:



var myButton = document.getElementById(myButton);
var myTextfield = document.getElementById(myTextfield);

function greetUser(userName) {
var greeting = Hello + userName + !;
document.getElementsByTagName (h2)[0].innerHTML = greeting;
}

myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);

return false;

}


Any Idea why I am getting the error?


More From » html

 Answers
28

Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.



document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).


[#81023] Sunday, January 6, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amberlykaliac

Total Points: 415
Total Questions: 100
Total Answers: 85

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;