0

This code is not working:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
document.getElementByID("button").addEventListener('click', outInfo, false);
function outInfo () {
var user =  document.getElementById("userName").value;
alert(user);
}
</script>
</head>
<body>
<p>User Name:
<input id="userName" type="text"/>
<input id="button" type="button" value="Click Me" />
</p>
</body>
</html>

This code is working:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
<script>
function output() {
var i = document.getElementById("input");
window.alert(i.value);
}
</script>
</head>
<body>
<p>User Name:
<input type="text" name="username" id="input" size="30"/>
<input type="button" id="button" value="Start" onclick="output()" />
</p>
</body>
</html>

What's wrong with the first one? I suppose the problem is with a function "outInfo". Which way is the best to solve such problems?

6
  • 1
    Elements don't exist yet. Add script before closing body tag. Commented Dec 12, 2013 at 22:48
  • 1
    Please make the title more descriptive. "Code is not working" is very vague. Commented Dec 12, 2013 at 22:48
  • 1
    Move the script tag to right before </body> Commented Dec 12, 2013 at 22:49
  • Which browser/version are u running this in? Commented Dec 12, 2013 at 22:50
  • Possible example... stackoverflow.com/questions/15255801/… Commented Dec 12, 2013 at 22:50

2 Answers 2

1

You are trying to run the javascript referring to an element before the document fully loads.

Do this:

HTML

<body onload='onLoad()'></body>

JS

function onLoad() {

  // ... Now manipulate my DOM
  document.getElementById("button").addEventListener('click', outInfo, false);

}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Consider accepting my answer if this did cause it to work out.
0

The element doesn't exist yet, when you try to bind the event to it.

You have to run the code after the element has been created, either by putting the code somewhere after the element:

<input type="button" id="button" value="Start" onclick="output()" />
<script>
document.getElementById("button").addEventListener('click', outInfo, false);
</script>

Or by using the load event that happens after the page is completely loaded:

document.onload = function(){
  document.getElementById("button").addEventListener('click', outInfo, false);
};

Note also that it's getElementById, not getElementByID.

1 Comment

very helpful answer - "Or by using the load event that happens after the page is completely loaded:"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.