Reputation: 3
So, I was going through a tutorial on event handlers. I created a button as instructed and then when I click on it, I wanted an alert to be displayed. Thats it. But it wouldn't work. Here's my html code:
<button id="submit">Submit</button>
And here's my javascript code:
var myButton = document.getElementByID("submit");
myButton.onclick = function(){
alert("YOu clicked on this button");
}
I am using external js file and I've included it in the html from the head of the document.
Upvotes: 0
Views: 3269
Reputation: 544
change from document.getElementByID
to document.getElementById
and make sure your script stay below all the elements in the body. Example:
<body>
<button id="submit">Submit</button>
<script type="text/javascript">
var myBtn = document.getElementById("submit");
myBtn.onclick = function()
{
alert("this is a click event button");
};
</script>
</body>
or you can put the script inside the <head></head>
by add this event below to your script:
function initialize()
{
// paste your code in here
}
document.addEventListener("DOMContentLoaded",initialize,false);
Hope it work!
Upvotes: 0
Reputation: 16595
You may have an issue where document.getElementById()
is happening before the element is created on the page. Try including your JavaScript in an onload event, or include it after the button in your HTML.
Upvotes: 1
Reputation: 340
As previously stated, use document.getElementById("submit") with lower case Id. Also, you may want to use setAttribute so the alert fires when the button is pressed instead of immediately opening a popup when the alert line is encountered.
<script language="javascript">
var myButton = document.getElementById("submit");
myButton.setAttribute("onclick", "alert('You clicked on this button')");
</script>
Upvotes: 0
Reputation: 10050
document.getElementByID("submit");
-- it's Id
instead of ID
Edit: I feel very bad for giving this one-liner as an answer, so to add to what others have said about learning how to use the browser's console as a debuggining tool, you should try to find an IDE/text editor with auto-completion to save you such headaches especially when you're just starting out.
Upvotes: 10