Reputation: 3036
I am struggling with the following piece:
<script>
$('button').click(function(){
alert("button clicked");
});
</script>
<button type="button" class="button-save">Save</button>
I do not get an alert when I click the button. I tried targeting the class with the button, but that didn't help either. I am trying to execute some ajax (not in my example of course) when I click the Save button like in this answer, so I need to find when the user clicked the button.
Can anyone help?
Upvotes: 0
Views: 2940
Reputation: 378
add this line in the head section of your html page
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
and rewrite your code to:
$( document ).ready(function() {
$('button').click(function(){
alert("button clicked");
});
});
Upvotes: 0
Reputation: 104775
You have to wait until your page is completely rendered to bind handlers, else the elements dont exist yet. You have two options, move your script
tags to after your HTML has been rendered:
<button type="button" class="button-save">Save</button>
<script>
$('button').click(function(){
alert("button clicked");
});
</script>
Or wrap your code in a DOM ready statement.
<script>
$(document).ready(function() {
$('button').click(function(){
alert("button clicked");
});
});
</script>
<button type="button" class="button-save">Save</button>
Upvotes: 2