A data-* attribute on an <input> tag attaches additional data to the input element.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-price
attribute on each checkbox.
The attribute values are not visible, but they are readable by JavaScript.
<input type="checkbox" value="Product 1" data-price="$4.99"> Product 1<br />
<input type="checkbox" value="Product 2" data-price="$8.04"> Product 2<br />
<input type="checkbox" value="Product 3" data-price="$2.77"> Product 3
The data-* attribute allows you to add custom attributes to a <input> element.
The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.
An <input> element can have any number of data-* attributes, each with their own name.
These attributes usually store additional data about the input (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 input tag in any way.
<input 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-price
attribute of each of the three checkbox elements.
Clicking a checkbox will display the price value.
<input type="checkbox" value="Product 1" data-price="$4.99" onclick="show(this);"> Product 1<br />
<input type="checkbox" value="Product 2" data-price="$8.04" onclick="show(this);"> Product 2<br />
<input type="checkbox" value="Product 3" data-price="$2.77" onclick="show(this);"> Product 3
<script>
let show = element => {
alert("Price = " + element.getAttribute('data-price'));
}
</script>
The <input> tag below contains a custom data-price
attribute.
The data-price
attribute specifies the price of the product.
Clicks are handled by the onclick
event.
Onclick invokes a JavaScript function that extracts and displays the checkbox <input> price.
Note: Notice how each price displays immediately 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 |