I'm trying to use JQuery so that when the user clicks on an HTML link, a function that I write in the JavaScript file is called.
<a href="#" id="advanced_options">Show advanced options</a>
And
$(document).ready(function() {
$("#advanced_options").click(function() {
alert('hello');
});
});
When I click on the link, it doesn't alert, but instead jump to another link. Why is that?
asked May 27, 2013 at 19:43
Mika H.
4,39913 gold badges49 silver badges64 bronze badges
2 Answers 2
If you're loading the link via an ajax query, so it's not on the page during the initial loading of the page use the jQuery on function: http://api.jquery.com/on/
$(document).ready(function() {
$(document).on( 'click' , "#advanced_options" , function(event) {
event.preventDefault();
alert('hello');
});
});
Sign up to request clarification or add additional context in comments.
Comments
You must prevent default browser behaviour:
$(document).ready(function() {
$("#advanced_options").click(function(event) {
event.preventDefault();
alert('hello');
});
});
answered May 27, 2013 at 19:46
moonwave99
22.9k3 gold badges49 silver badges71 bronze badges
Comments
lang-js
href="#". If you want a button that just does something with JS, and don't want to link to anything, then use an actual button and not a link.$(document).ready(function()it saysUncaught Type Error: Object #<HTMLDocument> has no method 'ready'. Butjquery.min.jsis clearly loaded. What's going on?<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>