当提交按钮被命名为“submit”时,为什么我的表单不提交?

时间:2021-10-18 17:55:07

I need to check if the form is submitted by the user and then perform some operation before subsequently submitting the form programmatically.

我需要检查表单是否由用户提交,然后在随后以编程方式提交表单之前执行一些操作。

So I have this code:

所以我有这个代码:

$('form').submit(function (e) {
    e.originalEvent && e.preventDefault();

     //I change some things in the form here.

    !e.isTrigger && $(this).submit();
}); 

This works fine, but when the form submit button is named "submit" it does not.

这可以很好地工作,但是当表单提交按钮被命名为“submit”时,它就不能工作了。

It even works ok if the button is named "Submit". (uppercase "S")

如果按钮被命名为“Submit”,它甚至可以正常工作。(大写字母“S”)

I'm just curious as to why this is?

我很好奇为什么会这样?

Here is a demo fiddle

这是一个演示小提琴。

1 个解决方案

#1


5  

You fell prey to some ancient DOM quirks. Namely, forms in the DOM get all their input elements (and buttons, too) exposed as properties by their respective name:

你被一些古老的多玛怪癖所折磨。也就是说,DOM中的表单通过它们各自的名称将所有输入元素(以及按钮)公开为属性:

<form>
  <input name="foo">
</form>

results in:

结果:

var form = document.forms[0];
form.foo === document.getElementsByName('foo')[0];

which is unfortunate, when you have any control with the name submit, because it shadows your original form's submit method.

这是很不幸的,当您有任何名称为submit的控件时,因为它会影响原始表单的submit方法。

Edit: By the way, for reading on many of those pitfalls I suggest to take a look at Kangax' fantastic DOMLint documentation.

编辑:顺便说一下,如果你想了解这些陷阱,我建议你看看Kangax的神奇DOMLint文档。

#1


5  

You fell prey to some ancient DOM quirks. Namely, forms in the DOM get all their input elements (and buttons, too) exposed as properties by their respective name:

你被一些古老的多玛怪癖所折磨。也就是说,DOM中的表单通过它们各自的名称将所有输入元素(以及按钮)公开为属性:

<form>
  <input name="foo">
</form>

results in:

结果:

var form = document.forms[0];
form.foo === document.getElementsByName('foo')[0];

which is unfortunate, when you have any control with the name submit, because it shadows your original form's submit method.

这是很不幸的,当您有任何名称为submit的控件时,因为它会影响原始表单的submit方法。

Edit: By the way, for reading on many of those pitfalls I suggest to take a look at Kangax' fantastic DOMLint documentation.

编辑:顺便说一下,如果你想了解这些陷阱,我建议你看看Kangax的神奇DOMLint文档。