简体   繁体   中英

jquery $(“#form”).submit() not getting called

I have a form on a page that requires a captcha if the user has a blocked attribute set in a database.

$("#expressform").submit(function() {
    if($("#op").val() == "")
            return false;
    if($("#tagbar").val() == "")
            return false;
    $.post("getallowed.php", function(data) {
            if(data == "true")
                    submitNormal();
            else if(data == "false"){
                    displayCaptcha();
            }
    });
    return false;
});

If the user is not allowed, the displayCaptcha function is called instead of just submitting the form.

function displayCaptcha(){
    $.post("expresscaptcha.php", function(data) {
            var string = data;
            $("#expressformdiv").html(string);
            Recaptcha.create("xxxxxxxxxxx", "captcha",
                    {
                            theme: "red",
                            callback: Recaptcha.focus_response_field
                    }
            );
    });
}

This function posts to a php script that returns a new type of form that returns the html for a new form with the id expressformcaptcha. Here is the php script.

<?php
echo <<<_END
<form id="expressformcaptcha">
    //other form elements
    <div id="captchadiv"><div id="captcha"></div></div>
</form>
_END;
?>

All of this works fine, the captcha displays, etc. However, the alert in the following never gets called. Why?

$("#expressformcaptcha").submit(function() {
    alert("FORM SUBMITTED");
});

Does it have something to do with the captcha being there that screws with jquery? When submit the form, instead of the alert, the page just refreshes.

You need to use live or delegate as expressformcaptcha is injected into the DOM at a later time.

$("#expressformcaptcha").live('submit', function() {
    alert("FORM SUBMITTED");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM