[removed] Form onSubmit does not work when function is called 'submit'

前端 未结 2 1946
别那么骄傲
别那么骄傲 2021-01-24 08:36

I am trying to call a JavaScript function when the submit button of a form is clicked.

For some reason, the function is not called when it is named \'submit\', but when

相关标签:
2条回答
  • 2021-01-24 08:51

    Because submit() is the reserved function to submit a form in core JS.

    For example, if your form had an id like myform, you could do this to submit it via JS:

    document.form['myform'].submit();
    

    So calling that function you're actually submitting the form and not calling your custom function.

    EDIT: I forgot to mention, it only works inside the form because it's calling the submit function of that form. Out of it it's not available anymore (since the body tag doesn't have a submit function).

    0 讨论(0)
  • 2021-01-24 09:14

    Form elements are placed on the scope chain of listeners within the form as if by:

    with (form) {
      /* run listener code */
    }
    

    so the identifier submit is first resolved in the context of the handler, then on the form before the rest of the scope chain. This is unique to forms and can be seen in the following:

    <form>
      <input name="foo">
      <input type="button" value="Do click" onclick="
        function submit(){console.log('click')};
        submit();
      ">
    </form>
    

    where clicking the button runs the submit function within listener, and removing the function declaration runs the form's submit method. This is unique to forms.

    Note that when a form's submit method is called directly, its submit handler is not called.

    Outside of the form, the identifier submit is resolved in the normal way.

    0 讨论(0)
提交回复
热议问题