HTMLSelectElement: thuộc tính selectedIndex

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Thuộc tính selectedIndex của giao diện HTMLSelectElement là chỉ số số học của phần tử <option> đầu tiên được chọn trong phần tử <select>, nếu có, hoặc −1 nếu không có <option> nào được chọn. Đặt thuộc tính này sẽ chọn option ở chỉ số đó và bỏ chọn tất cả các option khác, còn đặt thành -1 sẽ bỏ chọn mọi option đang được chọn.

Giá trị

Một số.

Ví dụ

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}`;
});

Đặc tả kỹ thuật

Specification
HTML
# dom-select-selectedindex-dev

Tương thích trình duyệt

Xem thêm