溫馨提示×

js怎么獲取下拉列表選中的值

js
小億
322
2023-08-05 09:18:08
欄目: 編程語言

在JavaScript中,可以通過以下方式獲取下拉列表(select元素)選中的值:

  1. 使用JavaScript的getElementById方法獲取下拉列表的DOM元素。

  2. 使用selectedIndex屬性獲取選中項的索引。

  3. 使用options屬性獲取下拉列表的所有選項。

  4. 使用選項的value屬性獲取選中項的值。

下面是一個示例代碼:

<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<script>
// 獲取下拉列表元素
var selectElement = document.getElementById("mySelect");
// 獲取選中項的索引
var selectedIndex = selectElement.selectedIndex;
// 獲取下拉列表的所有選項
var options = selectElement.options;
// 獲取選中項的值
var selectedValue = options[selectedIndex].value;
console.log(selectedValue);
</script>

在上面的示例中,selectElement.selectedIndex獲取選中項的索引,然后使用options[selectedIndex]獲取選中項的DOM元素,再通過.value獲取選中項的值。最后,使用console.log打印選中的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女