Can not stop submit event in Javascript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can not stop submit event in Javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I used this to validate my form but I can stop the submit event on my page. It still sends data and submit that. Why? How can I stop it?

    $(document).on("submit", "form", function(e) {
        if ($('#input-name').val() === '' && $('#input-phone-number').val() === '' && $('#input-address').val() === '' && $('#input-email').val() === '') {
            e.preventDefault();
            $('.noti-container').css({
                'opacity': '1',
                'z-index': '9999',
                'top': '20px',
                'background': '#FFCCCC'
            });
            $('.icon-container').html('<i class="fa fa-close"></i>');
            $('.notif').text('Please fill all field!');
            $('.notif').css({'color': 'black'});
            $('.icon-container').css({
                'background': '#F2F5A9'
            });
            setTimeout(function () {
                $('.noti-container').css({
                    'opacity': '0',
                    'z-index': '-1',
                    'top': '0',
                })
            }, 1500);
            return false;
        } else {
            return true;
        }
    });

Answer

e.preventDefault(); seems to be present in the if block. If the if condition resolves to false, the form will be submitted. You need to move e.preventDefault(); code before if block to prevent submission on all cases.

Example:

$(document).on("submit", "form", function(e) {
  e.preventDefault();
  // Remaining Code
}
We are here to answer your question about Can not stop submit event in Javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji