HTMLSelectElement: selectedIndex 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

selectedIndex 屬性是 HTMLSelectElement 介面的一個屬性,它表示一個 <select> 元素中第一個被選中的 <option> 元素的數值索引,如果沒有被選中的項,則返回 −1。設定此屬性會選中指定索引處的選項並取消選中所有其他選項;將其設定為 -1 會取消選中任何當前選中的選項。

一個數字。

示例

HTML

html
<p id="p">selectedIndex: 0</p>

<select id="select">
  <option selected>Option A</option>
  <option>Option B</option>
  <option>Option C</option>
  <option>Option D</option>
  <option>Option E</option>
</select>

JavaScript

js
const selectElem = document.getElementById("select");
const pElem = document.getElementById("p");

// When a new <option> is selected
selectElem.addEventListener("change", () => {
  const index = selectElem.selectedIndex;
  // Add that data to the <p>
  pElem.textContent = `selectedIndex: ${index}`;
});

規範

規範
HTML
# dom-select-selectedindex-dev

瀏覽器相容性

另見