The text
property sets or gets the text of an option element.
text |
Yes | Yes | Yes | Yes | Yes |
Return the text property.
var v = optionObject.text
Set the text property.
optionObject.text=text
Value | Description |
---|---|
text | Set the text of the option element |
A String type value representing the text of the option element.
The following code shows how to Change the text of an option element in a drop-down list.
<!DOCTYPE html>
<html>
<body>
<!--from w w w . j a v a 2 s .com-->
Select your favorite fruit:
<select>
<option id="C">C</option>
<option id="A">A</option>
<option id="P">P</option>
<option id="B">B</option>
</select>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
document.getElementById("C").text = "newTextForApple";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the text of the selected option in a drop-down list.
<!DOCTYPE html>
<html>
<body>
<!-- w w w.j a va 2 s . c o m-->
Select your favorite fruit:
<select onchange="myFunction(this)">
<option>A</option>
<option>O</option>
<option>C</option>
<option>R</option>
</select>
<p id="demo"></p>
<script>
function myFunction(selTag) {
var x = selTag.options[selTag.selectedIndex].text;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the text of all options in a drop-down list.
<!DOCTYPE html>
<html>
<body>
<!--from ww w .jav a2s. c o m-->
Select your favorite fruit:
<select id="mySelect">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
var i;
for (i = 0; i < x.length; i++) {
console.log(x.options[i].text);
}
}
</script>
</body>
</html>
The code above is rendered as follows: