Reputation: 653
I'm writing some simple jquery, and for some reason, I simply cannot make it work. I /know/ it works elsewhere, but I'm either missing something, or there's a bug on my webserver.
code follows:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>asdf</title>
<script src="jquery.js" type ="text/javascript"></script>
<script language ="javascript" type = "text/javascript">
//alert("number one");
$('#regSubmit').click(function(){
alert("Clicked!");
});
$('#test2').click(function(){
alert("yeah that worked.");
})
</script>
</head>
<body>
<input type ="button" id="regSubmit" value="Register!" />
<div id="test2">
Here is some other stuff!
</div>
</body>
</html>
So I've copied that code exactly, but it doesnt work for me. that commented out alert near the top (number one) works fine, so its calling the jquery, but no clicks register.
What am I doing wrong?
Upvotes: 1
Views: 62
Reputation: 50982
add your javascript to
$(function(){
//your code
});
This is needed, as you can only bind events to elements, they are already exist. At the moment you try this before they exist, this example code executes it after the full page is loaded, so all html is there
Upvotes: 3
Reputation: 14718
Your code when embedded into HTML is executed sequentially, so at the time of the execution of your code regSubmit and test2 are not yet defined.
Move your code to the bottom of the HTML document, or wrap it in $(function(){ /*your code here*/ });
which will defer your code execution until the entire document is loaded.
Upvotes: 1
Reputation: 700870
You are trying to bind events to elements before they exist. Run the code from the ready
event handler so that it runs when the whole document has loaded:
$(document).ready(function(){
$('#regSubmit').click(function(){
alert("Clicked!");
});
$('#test2').click(function(){
alert("yeah that worked.");
})
});
Upvotes: 0
Reputation: 28762
You'll have to either move the script to the bottom or wrap it in $(document).ready(function() { … }
. The document hasn't finished loading when the script executes, so when you try to attach the event handlers, the associated elements don't exist.
Upvotes: 1