Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - Why Form Elements should not be named submit?

I figured out through debugging that I should not name any Form Elements name="submit", but even after searching I didn't find any good explanation of why?

See simple code example below:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form action="javascript:alert('submitted');" method="post" id="test-form">
            <label>Name</label>
            <input type="text" name="name-field" value="" />
            <input type="submit" name="submit" value="Submit Button" /> <!-- name should not be "submit" -->
            <p><a href="javascript: document.getElementById('test-form').submit();">Submit Link</a></p>
        </form>
    </body>
</html>
  • If you Press Enter while on any Form Element or Click the Submit Button, it will work.
  • If you Click on the Submit Link, it will have error

    Unhandled Error: 'document.getElementById('test-form').submit' is not a function

If you simply rename your Submit Button to anything other than name="submit" (even if you just capitalize some part of it) or just remove the name="submit" attribute, then both the Submit Button and Submit Link will work.

I tried this in the latest version of Internet Explorer, Firefox, Opera, Chrome, and Safari. All of them have consistent behavior with regards to this.

As you can see in my code example, there is no involvement of jQuery or any other JavaScript library.

I would appreciate the explanation. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you check the Mozilla docs here : https://developer.mozilla.org/en-US/docs/DOM/HTMLFormElement

You will see that forms have a .submit() method.

In addition, forms are also populated with the fields within the form.

(Here is one example: http://www.devbay.com/articles/javascript/accessing-form-elements-array-with-javascript/ I can't find any reference that it should happen, only that it does.)

So, when you make an element called submit it over-rides the forms built-in submit() method -- and since the element is, well, not a function, you get that error message.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...