0

I've seen two methods of setting a form's action attribute.

#1. An empty action attribute:

action=""

#2. Action attribute with #:

action="#"

What are the differences between the two?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150

2 Answers2

6

The first one ("") resolves to the base URL, and the second one (#) resolves to the document URL.

The following is perfectly valid:

<form action="" method="post">
    <p><input type="submit"/></p>
</form>

Now beware, according to the HTML4 specification, the action attribute is mandatory, and it must contain a valid URI. But according to the URI RFC, an empty URI is still a URI:

A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML's FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request.

(extract from this page)


Although it is mandatory, most if not all browsers will post back to the originator of the response if no action attribute is specified.

And in HTML5, the action attribute is not mandatory. From the specs:

The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

Related:

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

The first resolves to the URL of the current page* (preserving any fragment identifier in the URL and you might as well omit the action attribute entirely), the other to the top of the page (erasing any fragment identifier that exists there already).


* Given normal URL resolution, I think it would resolve to the last / before the query string and fragment id in the URL of the current page, but HTML 5 special cases empty strings here (step 8) (presumably for backwards compatibility since most browsers have implemented it this way historically).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335