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>
</form>
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-id
, data-cost
, data-supplier
, etc.
Value | Description |
---|---|
value | A string value. Can be numeric, alphanumeric, JSON, etc. |
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>
</form>
<br/>
<button onclick="show();">Show data</button>
<script>
let show = () => {
let element = document.getElementById("myform");
alert("Form type = " + element.getAttribute('data-form-type'));
}
</script>
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.
Here is when data-* support started for each browser:
Chrome
|
1.0 | Sep 2008 |
Firefox
|
1.0 | Sep 2002 |
IE/Edge
|
1.0 | Aug 1995 |
Opera
|
1.0 | Jan 2006 |
Safari
|
1.0 | Jan 2003 |
Back to <form>