I have a really simple page with a form which I'm trying to prevent from sending with jQuery, but the code is surprisingly not working. Any ideas?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$("#searchForm").submit(function(e){
e.preventDefault();
});
</script>
</head>
<body>
<form id="searchForm">
<input name="q" placeholder="Go to a Website">
<input type="submit" value="Search">
</form>
<pre id="response"></pre>
</body>
You need to wrap your code in .ready()
so that it would get executed when the DOM is ready.
$(document).ready(function() {
$("#searchForm").submit(function(e){
e.preventDefault();
});
});
Your code is in the header so it executes before the <form>
even exists. Thus, the selector #searchForm
matches nothing. Put the script tag below the form.
You need to delay the addition of your event-listener function until the browser has finished loading the page. Otherwise those lines of JavaScript get executed before the form element exists, so the function doesn't get attached to it.
Wrap the event-listener in jQuery's .ready()
method:
$(document).ready(function() {
$('#searchForm').submit(function(event) {
event.preventDefault();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With