Jquery trap form submit()

前端 未结 4 1678
长情又很酷
长情又很酷 2021-01-02 00:58

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 c

相关标签:
4条回答
  • 2021-01-02 01:29

    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();
        }
    });
    
    0 讨论(0)
  • 2021-01-02 01:35

    Intstead of using the jQuery object to submit the form, you can use the DOM element that the jQuery object refers to to submit the form. This bypasses the jQuery event handler. Your OK function would look like this:

    "OK": function () {
        $dialog.dialog('close');
        $("#myform").get(0).submit(); // use the underlying DOM element to sumbit
        return false;
    },
    
    0 讨论(0)
  • 2021-01-02 01:36

    I would make something either a namespaced global, or a value from some hidden input like so:

    var something = nameSpaced.something ||  $('#hiddenInput').val(); //your choice
    if (something) {
        ...
    } ...
    

    Your logic should work normally then.

    0 讨论(0)
  • 2021-01-02 01:37

    You should return false when OK:

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

    Or delete the manual submit:

    buttons: {
    "OK": function () {
        $dialog.dialog('close');
        //$("#myform").submit();  <-- delete it
        return;
    },
    
    0 讨论(0)
提交回复
热议问题