1

I must have missed something.

I have a form:

<form action="/" method="post">
  <input type="text" name="field" required />
  <input type="submit" value="Submit" /> 
</form>

And I want to add a special behavior when then user clicks on the submit button without filling the required field. I have jQuery so my intuition wrote:

$('form').on('submit', function(e){
  console.log('Adding special behavior');
});

but this is not triggered. Looked for $('form').on('validate') or something, but could not find anything.

Ain't there any event triggered at this step? Do I have to remove the required and handle all the validation manually? That would be surprising!

Thanks


EDIT: this is no duplicate of this question since I don't (want to) use jquery.validate.js and my question doesn't rely on jQuery (I happen to use it but this simply helps for clarity). It's the HTML5 behavior that I wanted to clarify.

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

2 Answers2

3

When your input has a required attribute, the browser make sure the input is valid before submitting the form. Therefore, your event is never triggered.

However, you could add a novalidate attribute to your form to bypass the browser validation and perform your manual validation while keeping the required attribute on the inputs.

<form action="/" method="post" novalidate>
    <input type="text" name="field" required />
    <input type="submit" value="Submit" />
</form>

Also, if you want to stop the form from submitting normally, you have to do a preventDefault in your event.

$('form').on('submit', function(e){

    e.preventDefault();
    console.log('Adding special behavior');

});

Here's a demo: https://jsfiddle.net/nyecdfrj/

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • 1
    Interesting that my question is a duplicate of [this one](https://stackoverflow.com/questions/28123236/validate-form-before-submit-jquery) indeed, but the answer there is not satisfactory while yours is awesome! :) – Augustin Riedinger Nov 08 '17 at 15:03
0

Use the form onsubmit:

< form action="/" method="post" onsubmit="test()">

function test() {
return false; //never submit
}
Grenville Tryon
  • 120
  • 1
  • 1
  • 8