Using JQuery - preventing form from submitting

后端 未结 13 2965
灰色年华
灰色年华 2020-11-22 06:51

How do I prevent a form from submitting using jquery?

I tried everything - see 3 different options I tried below, but it all won\'t work:

    $(docu         


        
13条回答
  •  Happy的楠姐
    2020-11-22 07:23

    You may simply check if the form is valid if yes run submit logic otherwise show error.

    HTML

    Javascript

        $(document).ready(function () {
            var isFormValid = true;
    
            function checkFormValidity(form){
                isFormValid = true;
                $(form).find(".check-validity").each(function(){
                    var fieldVal = $.trim($(this).val());
                    if(!fieldVal){
                        isFormValid = false;
                    }
                });
            }
    
    
            //option A
            $("#form").submit(function (e) {
                checkFormValidity("#form");
                if(isFormValid){
                    alert("Submit Form Submitted!!! :D");
                }else{
                    alert("Form is not valid :(");
                }
                e.preventDefault();
            });
        });
    

提交回复
热议问题