Show form default Validation Status Programmatically

后端 未结 2 1012
孤街浪徒
孤街浪徒 2020-12-21 06:23

I want to submit a form using ajax. So I am not using the type=submit. I am using a onClick event on a link() to send the for

2条回答
  •  攒了一身酷
    2020-12-21 07:08

    You can do it if you let your form have a submit button and return false! And you cán do it in the same event handler as the non-submits! So, first test if you are part of a form and if so, make it check Validity and never return true (even if valid)!

    $('.ajx')   
        .on("submit click", function(e) {
    
            var $this           = $(this)
    
            //Force native form validating and notification
            form = $this.closest('form')[0]
            if (form) {
                //Follow through with form submit (element must be of submit type!)
                if(!form.checkValidity()) {
                    //don't ask me!
                    sleep(3000);
                    return false
                }
            }           
    
            //only preventDEfault AFTER possible form element click
            e.preventDefault()
    
            //...your project further ajax code
            //Makes sure your form never submits
            if (e.type=='submit') return false
    }
    

    Small downside: You have to do this on the submit button, but it's always possible to change your into type=submit. You don't have to change the non form 's though!

提交回复
热议问题