jQuery提交'this'表单

时间:2014-11-20 19:11:06

标签: javascript jquery

我尝试提交表单,一旦用户接受了他们想继续通过jQuery UI对话框。

<form method="POST" action="url" onsubmit="return APP.dom.confirm(this);">
   <button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
</form>

我的APP.dom.confirm方法如下:

 confirm: function(form) {
    $("#dialog-confirm").dialog({
       modal: true,
       buttons: {
          "Confirm": function() {
             $(form).submit();
          },
          "Cancel": function() {
             $(this).dialog("close" );
          }
       }
    });

    return false;
 }

这是有效的,但是当他们点击确认我想要提交的表单时。

$(form).submit();

这不起作用。记录下来我得到了上面的HTML。我尝试过变种,但无济于事:

$(form).clostest('form').submit();

如何提交this

2 个答案:

答案 0 :(得分:5)

更改

$(form).submit();

form.submit();

当您在jQuery对象上调用submit时,它会再次调用您的提交处理程序。直接在DOM元素上调用它不会。

示例(有趣的是,Stack Snippets不会让我提交表单,甚至不能使用target =&#34; _blank&#34;)

&#13;
&#13;
var nesting = 0;
function submitHandler(form) {
  var which = $(form).find("input[type=radio]:checked").val();
  ++nesting;
  if (nesting > 5) {
    snippet.log("Nested to 5, gave up");
  } else {
    if (which === "jQuery") {
      snippet.log("Calling via jQuery, nesting = " + nesting);
      $(form).submit();
    } else {
      snippet.log("Calling via DOM, nesting = " + nesting);
      form.submit();
    }
  }
  --nesting;
  return false;
}
&#13;
<form id="the-form"
      onsubmit="return submitHandler(this);"
      action="http://www.google.com/search"
      target="_blank"
      method="GET">
  <input type="text" name="q" value="kittens">
  <div>
    <label>
      <input type="radio" name="opts" value="jQuery"> Submit with jQuery
    </label>
  </div>
  <div>
    <label>
      <input type="radio" name="opts" value="DOM"> Submit with DOM
    </label>
  </div>
  <button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

confirm: function() {
var that = this;
    $("#dialog-confirm").dialog({
       modal: true,
       buttons: {
          "Confirm": function() {
             $(that).submit();
          },
          "Cancel": function() {
             $(this).dialog("close" );
          }
       }
    });
}

onsubmit="return APP.dom.confirm(this);"替换为
    $('form')。on('submit',APP.dom.confirm);