JavaScriptjQuery Callback on("submit") - Stack Overflow

Can someone tell me why this script doesn't work.I want the alert for "I just submitted the f

Can someone tell me why this script doesn't work.

I want the alert for "I just submitted the form" before "The form submitted." So I used a callback but it's still jumping past the submit.

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
    });
    callback();
}

formSubmit( function() {
    alert("The form submitted.");
});

HTML

<body>
    <form>
        <input type="submit"/>
    </form>
</body>
<script src=".1.3.min.js"></script>
<script src="js/forTesting.js"></script>

Can someone tell me why this script doesn't work.

I want the alert for "I just submitted the form" before "The form submitted." So I used a callback but it's still jumping past the submit.

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
    });
    callback();
}

formSubmit( function() {
    alert("The form submitted.");
});

HTML

<body>
    <form>
        <input type="submit"/>
    </form>
</body>
<script src="https://code.jquery./jquery-2.1.3.min.js"></script>
<script src="js/forTesting.js"></script>
Share Improve this question asked Oct 12, 2015 at 20:57 AryadneAryadne 732 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You must run your callback function within the jQuery event handler function (the second argument to on. Otherwise, callback will just execute immediately inside of formSubmit, but alert("I just submitted the form."); will only execute once the submit event occurs.

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
        callback();
    });
}

formSubmit( function() {
    alert("The form submitted.");
});

You need to call the callback after the alert, not after binding the submit handler.

function formSubmit(callback) {
    $("form").on("submit", function(e){
        e.preventDefault();
        alert("I just submitted the form.");
        callback();
    });   
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745084903a4610349.html

相关推荐

  • JavaScriptjQuery Callback on(&quot;submit&quot;) - Stack Overflow

    Can someone tell me why this script doesn't work.I want the alert for "I just submitted the f

    12小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信