Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

HTML <option> data-* Attribute

A data-* attribute on an <option> tag attaches additional data to the option item.

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

Example

#

A custom data-price attribute on <option> elements.
The attribute values are not visible, but they are readable by JavaScript.

<select>
  <option data-price="">-- Select size -- </option>
  <option data-price="+$0.50">Small</option>
  <option data-price="+$1.75">Medium</option>
  <option data-price="+$2.25">Large</option>
</select>

Using data-*

The data-* attribute adds custom information to an <option> element.

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

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

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

Note: The data-* attribute is not visible and does not change the appearance of the option.


Syntax

<option data-*="value">

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


Values

#

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

More Examples

A custom data-price attribute on each <option> tag.
Clicking the button will display the price value of the selected option.


<select id="selectoption">
  <option data-price="">-- Select size -- </option>
  <option data-price="+$0.50">Small</option>
  <option data-price="+$1.75">Medium</option>
  <option data-price="+$2.25">Large</option>
</select>

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

<script>
  let show = () => {
    let element = document.getElementById("selectoption");
    let price = element.options[element.selectedIndex].getAttribute("data-price");
    alert("Price: " + price);
  }
</script>

Code explanation

Each <option> tag has a custom data-price attribute.

The data-price attribute specifies the price of the <option>.

Clicking the button will display the selected <option> price.

Note: Notice how the price displays immediately without server call.


Browser support

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

You may also like

 Back to <option>
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

Guides