I have a button inside a form like this:
<form>
<input type="text" />
<input type="password" />
<button type="button" class="btn-login">Log in</button>
</form>
I am trying to trigger the button's click event by doing this in the js:
$(document).ready(function () {
$('.btn-login').live("click", function () {
alert("Button clicked!");
});
});
But for some reason, this is not working.
If I remove the <form></form>
that is around the textboxes and button, the click event is triggered, but this also means that my page is not showing properly, so I wonder if there is a way to trigger the button's click event when inside the form.
If you are using latest version of Jquery the try
on
instead oflive
as it is deprecated in version 1.9. If you are using version 1.7 then your code will work.JS Fiddle .on() example
JS Fiddle .live() example
I think below code should work for you
It uses delegate from jquery, so even if it is added later in DOM via ajax, this function would work.
instead of
use
My guess is that you are using a newer version of jquery, I tested with 1.9.1 and jQuery.live does not work (removed jquery 1.9). A simple change to jQuery.on and it sprang immediately to life.
on jsfiddle
As a note to comments, this is what the W3C has to say
This article demonstrates some of the differences between button and input
And what of W3cschools advice?
w3cschools are not an authorative body. As far as I can tell, the only browsers that had real issues were IE6 & IE7, so I guess their advice is a little out of date. It is possible that there are others but I could not find anything concrete. the best I could find was on MDN <\button>
.live Function() has been removed as from jQuery 1.9 . Reference: http://api.jquery.com/live/
Please use .on() function for binding events. Reference: http://api.jquery.com/on/
Solution:
You can migrate 1.1.0 to 1.9.1 to use
.live()
[Working Example] (http://jsfiddle.net/3hQbG/)