Prevent form submission on enter key

How can I prevent the enter key from submitting the form in angular?

Is there a way to catch the 13 key and disable it or set the form as invalid unless submitting from a button with ID of x?

Thanks


Since you have ng-click anyways, you could also use <button type="button">, even inside the form tag. The default behaviour of the button element is type="submit", which is what you want to prevent. So, no javascript needed at all!


Other users have already written that [button type="submit"] will cause this trouble. PLEASE NOTE: buttons WITHOUT any type="..." declaration are "submit" by default! So make sure you always use type="button".


After a couple hours, this weird code was the only thing that worked.

I'm waiting for better answers, won't accept this monster:

app.directive('onKeyup', function() {
    return function(scope, elm, attrs) {
      var allowedKeys = scope.$eval(attrs.keys);
      elm.bind('keydown', function(evt) {           
        angular.forEach(allowedKeys, function(key) {
          if (key == evt.which) {
             evt.preventDefault(); // Doesn't work at all
             window.stop(); // Works in all browsers but IE    
             document.execCommand("Stop"); // Works in IE
             return false; // Don't even know why it's here. Does nothing.                     
          }
        });
      });
    };
});

and trigger it by using this on all form inputs:

<input on-keyup="bla" keys="[13]" .... />

For now, whenever the user press the enter key, the window try to submit, then fail to do so, not so silently. Ugly but it works.

Edit: keydown is a little better than keyup for the element bind, now enter key fails silently-ish


so simple, doesn't need to do anything. just add this to your form tag if you are using angular +2

<form (keydown.enter)="$event.preventDefault()" ...>