HTML <form> data-* Attribute

A data-* attribute on a <form> tag attaches additional data to the form.

To create a custom attribute, replace * with a lowercase string, such as data-id, data-status, or data-location.



A data-type attribute on a <form>.
The attribute value is not visible, but it is readable by JavaScript.

<form data-type="registration" action="/tutorial/action.html">
  <input type="text" name="firstname" placeholder="First Name">
  <input type="text" name="lastname" placeholder="Last Name">

  <button type="submit">Submit</button>

Using data-*

The data-* attribute allows you to add custom attributes to a <form> element.

The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.

An <form> element can have any number of data-* attributes, each with their own name.

These attributes usually store additional data about the form (e.g. id, options, variations, etc.).

Using data-* attributes reduces the need for Ajax requests to the server.

Note: The data-* attribute does not change the appearance of the form tag in any way.


<form data-*="value">

Note: The * can be any string, such as data-iddata-costdata-supplier,  etc.



Value Description
value A string value. Can be numeric, alphanumeric, JSON, etc.

More Examples

A custom data-form-type attribute on a <form> element.
Clicking the button displays the form type.

<form id="myform" data-form-type="Registration form" action="/tutorial/action.html">
  <input type="text" name="firstname" placeholder="First name">
  <input type="text" name="lastname" placeholder="Last name">
  <button type="submit">Submit</button>

<button onclick="show();">Show data</button>

  let show = () => {
    let element = document.getElementById("myform");
    alert("Form type = " + element.getAttribute('data-form-type'));

Code explanation

The <form> tag below assigned the data-form-type attribute.

The data-form-type attribute specifies the type of form.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the form type.

Note: Notice how the form type displays quickly without server call.

Browser support

Here is when data-* support started for each browser:

1.0 Sep 2008
1.0 Sep 2002
1.0 Aug 1995
1.0 Jan 2006
1.0 Jan 2003

You may also like

 Back to <form>

Last updated on Sep 30, 2023