0

I'm trying to bind some manual validation to the on('submit') event in jQuery after pausing the submission, but have it still perform the browser's native HTML validation. However, I cannot get it to work.

This is my bare-bones code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Prevent Form Submission</title>
</head>
<body>
    <form>
        <input type="text" name="example" required>
        <input type="submit">
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
        $(document).on('click', 'input[type=submit]', function(e) {
            e.preventDefault();
            // Do something here
            $('form').submit();
        });
    </script>
</body>
</html>

With this code, I can prevent the form from submitting, but then when I run the submit() event it "skips" the HTML validation and just submits, even if the required field is empty. I am using Google Chrome Version 67.0.3396.99 (Official Build) (64-bit).

If I change the jQuery to this:

$(document).on('submit', 'form', function(e) {
    e.preventDefault();
    // Do something here
    $(this).submit();
});

I cannot even get it to submit.

Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
mpdc
  • 3,550
  • 5
  • 25
  • 48
  • 1
    Possible duplicate of https://stackoverflow.com/questions/7548612/triggering-html5-form-validation – CBroe Jul 02 '18 at 14:56
  • You have to think that every browser will show the HTML validation in different ways, so perhaps it's more interesting to make the validation yourself by JQuery. Anyway, the answer from CBroe seems correct. – Ricard Espinàs Llovet Jul 02 '18 at 14:59
  • So nobody knows when the actual HTML validation happens? i.e. on which event, so we can work around it? – mpdc Jul 02 '18 at 15:12

1 Answers1

0

I managed to get this working by using Javascript's native this as opposed to jQuery's $(this).

$('form').on('submit', function(e) {
    var form = this;
    e.preventDefault();
    // Do something
    form.submit();
});
mpdc
  • 3,550
  • 5
  • 25
  • 48