Sinan Samet
Sinan Samet

Reputation: 6752

Submit form after preventDefault and unbind

I used preventDefault on my form and I am trying to use this to automatically submit when a statement is true.

function codeCheck(){
        $("#code-form").submit(function(e){
            e.preventDefault();
        });
        var code = $("#code").val();
        $.ajax({
            url: "index.php",
            type: "POST",
            data: { codeCheck: 1, ajaxCode: code }
        }).done(function(check) {
            if(check == 2){
                $("#used").css("display", "block");
            }
            else if(check == 1){
                $("#code").css('background', "url('../img/check.png') no-repeat scroll 170px 2px");
                $("#submit").css('display', 'block');
                $("#submit").on("click", function(){
                    $( "#container" ).fadeOut( "slow", function() {
                        $("#code-form")[0].submit();
                    });
                });

                $("#used").css("display", "none");
            }
            else{
                $("#code").css('background', "none");
                $("#used").css("display", "none");
                //$("#code-form").unbind('submit');
            }
        }); 
}

The unbind does work I can use the submit button when I unbind it. But the $("#form").submit() part doesn't work it doesn't submit the form automatically after fading out.

Here is a fiddle: http://jsfiddle.net/90wmpw7x/1/

All I want is that it continues the form after the fade.

EDIT: For more clarity I just added the full function.

Upvotes: 2

Views: 10413

Answers (2)

PeterKA
PeterKA

Reputation: 24638

You want to use the following, since, you say submit event is already prevented. This will submit the form in the default manner:

$("#form")[0].submit();

Instead of:

$("#form").unbind('submit', function(){
    $("#form").submit();    
});

Special Note:

For this to work, ensure you do not have any form field with name="submit".

UPDATE

Given the updated code, here is my recommendation:

$("#form").submit(function(e){
    e.preventDefault();

    $( "#container" ).fadeOut( "slow", function() {
        $("#form")[0].submit();    
    });
});

The fadeOut code should be moved to inside the submit handler

DEMO

Upvotes: 4

Amit Joki
Amit Joki

Reputation: 59252

You don't need to unbind() as the page is refreshed and all event handlers will be destroyed.

$("#container").fadeOut("slow", function() {
    $("#form").submit();
});

But, if you've event handler attached and you do posting through ajax and want to unbind that event, then you can use chaining

$('#form').unbind('submit').submit();

Upvotes: 1

Related Questions