CKTIS / JavaScript
HTMLOptionElement.value — the value of an HTML option
Read or set the value of one HTML option. A missing `value` attribute makes the property fall back to the option’s text, but an explicitly empty value stays empty.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
option.value
option.value = newValueHTMLOptionElement.value is a read/write property on an individual option element. Reading it returns a string whether or not the option is selected. If the HTML value attribute is present, the property returns its contents, even "". Only when the attribute is absent does the property fall back to the option’s text: leading and trailing ASCII whitespace is stripped, and internal runs collapse to one space. The label attribute is not the source of that fallback.
Assigning to option.value creates or updates the value attribute without changing the option’s text or selection state. option.removeAttribute("value") restores the text fallback. Set an explicit value such as "plan-pro" when the identifier needs to stay the same even if the displayed wording changes or is translated.
By contrast, reading select.value gives the value of the first selected option in DOM tree order, or "" if none is selected. An empty result therefore does not prove that nothing is selected. This is a DOM API defined by the HTML Standard, not part of ECMAScript; the example requires an environment that provides the HTML DOM.
Examples
<!doctype html>
<meta charset="utf-8">
<title>HTMLOptionElement.value example</title>
<script>
const option = document.createElement("option");
option.textContent = " Pro\n plan ";
console.log(JSON.stringify([option.value, option.getAttribute("value")]));
option.value = "";
console.log(JSON.stringify([option.value, option.getAttribute("value")]));
option.value = "plan-pro";
console.log(JSON.stringify([option.value, option.text]));
option.removeAttribute("value");
console.log(JSON.stringify([option.value, option.getAttribute("value")]));
</script>Result
["Pro plan",null] ["",""] ["plan-pro","Pro plan"] ["Pro plan",null]
Save the example as an HTML file and open it in a browser. View the output in the developer console. `null` means the attribute is absent, not empty: on the second line, the attribute is present and contains `""`. The element does not need to be added to the page.
Related lessons
- JavaScript · Lesson 43 · Intermediate · Version: 3