Programming Tutorials

(追記) (追記ここまで)

Handling Select options in JavaScript

By: aathishankaran in JavaScript Tutorials on 2007年03月27日 [フレーム]

In HTML, a <select> element creates a drop-down list. The options in the drop-down list can be accessed and manipulated using JavaScript.

To get the selected option from a <select> element, you can use the selectedIndex property and the options property of the element. Here's an example:

<select id="mySelect">
 <option value="option1">Option 1</option>
 <option value="option2">Option 2</option>
 <option value="option3">Option 3</option>
</select>
<script>
 const selectElement = document.getElementById("mySelect");
 const selectedOption = selectElement.options[selectElement.selectedIndex].value;
 console.log(selectedOption); // prints the value of the selected option
</script>

To change the selected option in a <select> element using JavaScript, you can set the selectedIndex property to the index of the option you want to select. Here's an example:

<select id="mySelect">
 <option value="option1">Option 1</option>
 <option value="option2">Option 2</option>
 <option value="option3">Option 3</option>
</select>
<button onclick="changeOption()">Change option</button>
<script>
 const selectElement = document.getElementById("mySelect");
 
 function changeOption() {
 selectElement.selectedIndex = 1; // selects the second option
 }
</script>



(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /