Skip to main content

Form Attributes

Form Attributes

Form attributes in HTML define the behavior and functionality of forms. Understanding these attributes helps in creating forms that are efficient, secure, and user-friendly. This guide provides an overview of various form attributes, along with examples to illustrate their usage.


Action attribute

The action attribute specifies the URL to which the form data will be submitted.

<form action="/submit-form">
  <input type="text" name="username" placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Method attribute (GET vs POST)

The method attribute specifies the HTTP method to be used when submitting the form. Common values are GET and POST.

GET: Data is appended to the URL. Suitable for non-sensitive data.

<form action="/search" method="get">
  <input type="text" name="query" placeholder="Search">
  <input type="submit" value="Search">
</form>

POST: Data is sent in the request body. Suitable for sensitive data.

<form action="/submit-form" method="post">
  <input type="text" name="username" placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Target attribute

The target attribute specifies where to display the response after submitting the form. Common values include _self, _blank, _parent, and _top.

<form action="/submit-form" target="_blank">
  <input type="text" name="username" placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Enctype attribute

The enctype attribute specifies the encoding type to be used when submitting the form data. It is used with the POST method.

Common values:

  • application/x-www-form-urlencoded: Default. Encodes form data as key-value pairs.
  • multipart/form-data: Used for file uploads.
  • text/plain: Encodes form data as plain text (not recommended).
<form action="/submit-form" method="post" enctype="multipart/form-data">
  <input type="file" name="fileupload">
  <input type="submit" value="Upload">
</form>

Autocomplete attribute

The autocomplete attribute specifies whether a form or input field should have autocomplete enabled. Values can be on or off.

<form action="/submit-form" autocomplete="on">
  <input type="text" name="username" placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Novalidate attribute

The novalidate attribute specifies that the form should not be validated when submitted. It is a boolean attribute.

<form action="/submit-form" novalidate>
  <input type="text" name="username" placeholder="Enter your name">
  <input type="submit" value="Submit">
</form>

Conclusion

Understanding and utilizing form attributes in HTML is essential for creating effective and secure web forms. These attributes provide control over the form's behavior and ensure a better user experience.

Comments