jquery陷阱表单提交() [英] Jquery trap form submit()

查看:128
本文介绍了jquery陷阱表单提交()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用jquery来捕获表单的提交并向用户显示确认对话框。如果用户点击是,则表单应提交。如果用户单击否,则关闭对话框。

I'm currently using jquery to trap the submission of a form and show users a dialog for confirmation. If user clicks yes, then form should submit. If user clicks no, then close the dialog.

这一切都很有效,但有一个问题:当用户点击yes时,它会再次触发相同的代码,并重新打开对话框。

This all works well but for one issue: when the user clicks yes, this then triggers the same code again, and the dialog is re-opened.

$("#myform").submit(function (event) {
    if (something) {
        var $dialog = $('<div></div>').dialog({
            buttons: {
                "OK": function () {
                    $dialog.dialog('close');
                    $("#myform").submit();
                    return;
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
        $dialog.dialog('open');
        event.preventDefault();
        return false;
    } else {
        $("#myform").submit();
    }
});

我明白为什么会发生这种情况,只是不确定最好的解决办法。我意识到我可以在按钮点击时显示模式,而不是表单提交,但是这并没有解决用户敲击键盘上的输入按钮以提交表单的问题。

I understand why this is happening, just not sure on the best way to get around it. I realise that I could show the modal on button click, instead of form submit, but this doesnt get around the problem of user hitting enter button on keyboard to submit the form.

推荐答案

因为当 submit 表单时, submit 事件会再次触发,所以事件处理程序。当用户说 OK 时,您需要 unbind submit 事件处理程序>。试试这个

Because when you submit the form, the submit event triggers again and so the event handler. You need to unbind the submit event handler when user says OK. Try this

$("#myform").submit(function (event) {
    if (something) {
        var $dialog = $('<div></div>').dialog({
            buttons: {
                "OK": function () {
                    $dialog.dialog('close');
                    //Check this line - unbinding the submit event handler
                    $("#myform").unbind('submit').submit();
                    return;
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
        $dialog.dialog('open');
        event.preventDefault();
        return false;
    } else {
        $("#myform").submit();
    }
});

这篇关于jquery陷阱表单提交()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆