Reputation: 471
I have this simple jQuery click event, and for some reason it isn't working. The $(document).ready(function() {});
works, and I can use alerts inside of that; however the actual click event isn't working.
Thanks in advance, and please be easy on me as I haven't had much experience with jQuery. Thanks! :)
Here's my code:
script.js:
$(document).ready(function() {
alert("I can alert here");
$("#the_id").click(function() {
alert("I can't alert here");
});
});
HTML:
// This is an <input> instead of a <button> because I will be creating an AJAX call later
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input type="submit" id="the_id">
<script type="text/javascript" src="script.js"></script>
Upvotes: 1
Views: 1444
Reputation: 331
you could also use
$("#the_id").submit(function() {
// code will run before submitting form
});
Upvotes: 0
Reputation: 59292
The input
is of type submit
. So, it will trigger a post back, which results in a page refresh. Use event.preventDefault()
or change the type to button
.
<input type="button" id="the_id" />
Or event.preventDefault()
, after which you'll have to use ajax to send data to the server.
$(document).ready(function() {
alert("I can alert here");
$("#the_id").click(function(e) {
e.preventDefault(); // prevents the default action of submit
alert("I can't alert here");
});
});
Upvotes: 1