toastr.js disabling the required HTML5 property

Asked

Viewed 320 times

3

I am using toastr.js to display form validation messages, but when using this plugin it disabled all my inputs that had the property required.

My code:

<!DOCTYPE html>
<html>
    <head>
        <title>TOASTR</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.css">
        <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.js"></script>
    </head>
    <body>
        <form>
            <p>First Name: <input type="text" name="firstname" required></p>
            <p>Last Name: <input type="text" name="lastname" required></p>
            <p><button class="btnsubmit" type="submit" value="submit" data-toastr="success" data-message="Thanks for your donate.">Submit</button></p>
        </form>
        <script>
            toastr.options.closeButton = true;

            $('[data-toastr="success"]').on('click', function (event) {
                event.preventDefault();

                toastr.success($(this).data('message'));
            });
        </script>
    </body>
</html>

Does anyone know why?

1 answer

2


Well, the main reason for this is that you’re using the method .preventDefault(), on a button submit, that is, it will not cause the form to be submitted. Validation by required only happens at the time of submission.

If you want validation, and only then toastr.js get into action, can put, instead of event click in the input:submit, an event submit in the form:

toastr.options.closeButton = true;

$('#toastrForm').on('submit', function (event) {
    event.preventDefault();
    toastr.success($('[data-toastr="success"]').data('message')); // ao invés do $(this) usei o método de seleção anterior...
});

Thus, the call of the toastr will only happen after the submission, that is, before the validation will take place by required.

Working - Jsfiddle

  • Samir Braga, +1, perfect, worked smooth smooth, and thank you so much for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.