Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreventDefault not preventing form to send

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>

like image 408
user3169790 Avatar asked Jul 20 '14 06:07

user3169790


3 Answers

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();
     });
});
like image 165
martynas Avatar answered Oct 17 '22 17:10

martynas


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.

like image 31
Raphael Schweikert Avatar answered Oct 17 '22 17:10

Raphael Schweikert


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();
  });
});
like image 2
2540625 Avatar answered Oct 17 '22 17:10

2540625