user2158382
user2158382

Reputation: 4510

Javascript to run on form submit

I am having some issues getting some javascript code to run whenever a form is submitted.

Here is my code

   <form onsubmit="return header_search()" class="navbar-form navbar-right">
      <div class="form-group">
         <input type="text" placeholder="Tack" class="form-control">
      </div>
      <button type="submit" class="btn btn-success">Search</button>
   </form>

   <script>
       function header_search() {
          e.preventDefault();
          alert("submitted");
       } 
   </script>

http://jsfiddle.net/Fgwzn/

Upvotes: 0

Views: 300

Answers (3)

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

As @Quentin said, it's not behaving as expected because you are not defining e anywhere.

As you tagged jQuery, I'll suggest an alternative using it. Add an ID to your form and then define your onsubmit behavior in JavaScript.

HTML

<form id="your-form" class="navbar-form navbar-right">
    ...
</form>

JavaScript

$('#your-form').submit(function(e) {
    alert('submitted');
    e.preventDefault();
});

I think this would be the easier solution as you would not have to deal with browser compatibility issues (hey IE, I'm looking at you) with the event variable and addEventListener/attachEvent. jQuery takes care of that for you.

Fiddle: http://jsfiddle.net/MGA74/

Upvotes: 2

Onur Topal
Onur Topal

Reputation: 3061

if you try to cancel the submittion just user return false; in your code or use return false; in the onsubmit

like below

   <script>
       function header_search() {
          alert("submitted");
          return false;
       } 
   </script>

or

<form onsubmit="header_search(); return false;"...

Edit: e.preventDefault(); is not needed. also return is not needed in the form tag.

Upvotes: 0

Quentin
Quentin

Reputation: 943193

You never define e, so e.preventDefault(); throws an exception and the script stops.

You can either remove e.preventDefault(); or move to a modern event binding style:

Stop using intrinsic event attributes, bind your event handler with JS and make sure you accept an argument for the event object.

function header_search(e) {
  e.preventDefault();
  alert("submitted");
} 
document.querySelector('form').addEventListener('submit', header_search);

Reading the documentation (MDN is a good place to look) on browser support for and alternatives to querySelector and addEventListener is left as an exercise for the reader.

Upvotes: 1

Related Questions