i Have html code like this
<button>Button One</button>
<button>Button Two</button>
<button>Button Three</button>
<input type="Text" value="Content Text">
<a href="somewhere.php">URL</a>
I need Get event if any button click
i was tried use :
$(":button").click(function() {
alert("button click");
});
Thanks For Help
i Have html code like this
<button>Button One</button>
<button>Button Two</button>
<button>Button Three</button>
<input type="Text" value="Content Text">
<a href="somewhere.php">URL</a>
I need Get event if any button click
i was tried use :
$(":button").click(function() {
alert("button click");
});
Thanks For Help
Share Improve this question asked Mar 19, 2015 at 8:12 ArtronArtron 2661 gold badge5 silver badges13 bronze badges 3- What you tried should have worked, can you provide an MCVE? – T.J. Crowder Commented Mar 19, 2015 at 8:16
-
Side note: Beware that if those buttons are in a form, they will submit it. The (surprising) default
type
ofbutton
elements is"submit"
. – T.J. Crowder Commented Mar 19, 2015 at 8:16 - mostly you will have to use document ready handler – Arun P Johny Commented Mar 19, 2015 at 8:17
3 Answers
Reset to default 4What you have will work thanks to jQuery's custom :button
selector provided the buttons exist as of when you run your code. In order for them to exist, either:
You must have your code in a
script
element that's after the buttons in the HTML (just before the closing</body>
tag is best), orYou must use jQuery's
ready
callback to wait until the elements have been createdYou must delay execution of the code another way, such as a
window
load
callback, but that's very late in the page load process
Note that using jQuery's custom CSS selectors may not be ideal, you might want to change $(":button")
to $("button")
or $("button, input[type=button]")
so that jQuery can hand it off to the browser's built-in CSS selector engine.
Example of #1:
<button>Button One</button>
<button>Button Two</button>
<button>Button Three</button>
<input type="Text" value="Content Text">
<a href="somewhere.php">URL</a>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(":button").click(function() {
alert("button click");
});
</script>
Example of #2:
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() { // Or: `$(document).ready(function() {`, they're the same
$(":button").click(function() {
alert("button click");
});
});
</script>
<button>Button One</button>
<button>Button Two</button>
<button>Button Three</button>
<input type="Text" value="Content Text">
<a href="somewhere.php">URL</a>
Try this : remove :
. This is tag selector which has no .
, no :
or no #
but just tag name.
$("button").click(function() {
alert("button click");
});
More information on jQuery Selectors
Just remove :
from your .click
event.
There is a fiddle for you : http://jsfiddle/u1q6obLz/
Read more about jQuery selectors HERE