I trying to get onclick work, but it does not... Here is my code:
HTML
You need to wait for the document to be ready. You are attempting to attach a click event on something the page does know exists yet.
Fixes range from:
$(document).ready(function () { ... });
or $(function() { ... });
Of course I'd start with justifying the use of jQuery if all you're using it for is to attach and event listener, but that's just me.
Good luck
While the accepted answer (using ready
) works, it's not best practice.
Best practice is to put your script
tags at the end of the document, just before the closing </body>
tag, note the comments below:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<head>
<title>jQuery alert test</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- NO SCRIPTS HERE -->
</head>
<body>
<div class="container">
<div class="text-center">
<a class="btn btn-primary" id="submit">Submit</a>
</div>
</div>
<!-- SCRIPTS GO HERE -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$('#submit').click(function(){
alert('This onclick function forks!');
});
</script>
</body>
</html>
That way
The elements exist when your code runs
Downloading the external scripts doesn't hold up the display of your page
More in the YUI Best Practices for Speeding Up Your Web Site.
Your JS is being exucuted before the DOM elements have loaded. Your event handler is therefore not being attached to the element since it doesn't exist at the time.
Wrap your JS with a DOM ready handler:
$(document).ready(function () {
$('#submit').click(function(){
alert('This onclick function forks!');
});
});
You could also just use event delegation since the document
object exists at the time of execution:
$(document).on('click', '#submit', function () {
alert('This onclick function forks!');
});
Maybe JQuery library is missing..then add this on you code:
$(document).ready(function(){
...code here..
});