skip to Main Content

In my code’s else condition I want to remove preventDefault() and submit the form.

I don’t know to do this?

if(email.val() != ""){
            //check email
            e.preventDefault();
            $.ajax({
                type: 'post',
                url: '/register/check-email',
                data: {email: email.val()},
                success: (data) => {
                    console.log(data);
                    if(data == 1){
                        name.css('border', '1px solid #248ea9');
                        email.css('border', '1px solid red');
                        $("div.wrapper div.right div.form form small.error-name").hide();
                        $("div.wrapper div.right div.form form small.error-email").hide();
                        $("div.wrapper div.right div.form form small.error-email-found").show();
                    }else{
                        //remove preventDefault()
                    }
                }
            })
        }

2

Answers


  1. I guess you executed e.preventDefault () in the button of a form, this will prevent the submit of the form, if you want to continue to submit you can use the submit() method of the form directly, like this:

    if(email.val() != ""){
                //check email
                e.preventDefault();
                $.ajax({
                    type: 'post',
                    url: '/register/check-email',
                    data: {email: email.val()},
                    success: (data) => {
                        console.log(data);
                        if(data == 1){
                            name.css('border', '1px solid #248ea9');
                            email.css('border', '1px solid red');
                            $("div.wrapper div.right div.form form small.error-name").hide();
                            $("div.wrapper div.right div.form form small.error-email").hide();
                            $("div.wrapper div.right div.form form small.error-email-found").show();
                        }else{
                            //remove preventDefault()
                            // get form and submit
                            $("#form").submit()
                        }
                    }
                })
            }
    
    Login or Signup to reply.
  2. it dose not matter where do you put the e.preventDefault() at the or at the bottom it will work the same.

    if you have the action on the form you can put it right after you start the block of submit function.

    var submit = function (e) {
        e.preventDefault()
    }
    

    i don’t know about your case very much but you can use other methods like:

    e. stopPropagation();

    e.stopImmediatePropagation();

    for further read : https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search