HTMLSelectElement: selectedOptions 屬性
只讀的 HTMLSelectElement 屬性 selectedOptions 包含一個列表,其中列出了當前被選中的 <option> 元素。這個已選項列表是一個 HTMLCollection 物件,其中每個當前選中的選項都有一個條目。
如果選項具有 HTMLOptionElement.selected 屬性,則認為該選項被選中。
值
一個 HTMLCollection,列出了所有當前被選中的 HTMLOptionElement,它們或者是 HTMLSelectElement 的子元素,或者是 <select> 元素內 HTMLOptGroupElement 的子元素。
換句話說,<select> 元素內的任何選項都可能包含在結果中,但選項組(option groups)不包含在此列表中。
如果沒有選項被選中,則該集合為空,其 length 為 0。
示例
在此示例中,使用一個包含多個選項的 <select> 元素,讓使用者訂購各種食品。
HTML
建立選擇框和代表每種食品選擇的 <option> 元素的 HTML 如下所示:
html
<label for="foods">What do you want to eat?</label><br />
<select id="foods" name="foods" size="7" multiple>
<option value="1">Burrito</option>
<option value="2">Cheeseburger</option>
<option value="3">Double Bacon Burger Supreme</option>
<option value="4">Pepperoni Pizza</option>
<option value="5">Taco</option>
</select>
<br />
<button name="order" id="order">Order Now</button>
<p id="output"></p>
<select> 元素被設定為允許選擇多個專案,並且它有 7 行高。還請注意 <button>,它的作用是觸發使用 selected 屬性來獲取已選元素集合。
JavaScript
設定按鈕事件處理程式以及事件處理程式本身的 JavaScript 程式碼如下所示:
js
let orderButton = document.getElementById("order");
let itemList = document.getElementById("foods");
let outputBox = document.getElementById("output");
orderButton.addEventListener("click", () => {
let collection = itemList.selectedOptions;
let output = "";
for (let i = 0; i < collection.length; i++) {
if (output === "") {
output = "Your order for the following items has been placed: ";
}
output += collection[i].label;
if (i === collection.length - 2 && collection.length < 3) {
output += " and ";
} else if (i < collection.length - 2) {
output += ", ";
} else if (i === collection.length - 2) {
output += ", and ";
}
}
if (output === "") {
output = "You didn't order anything!";
}
outputBox.textContent = output;
});
此指令碼在“立即訂購”按鈕上設定了一個 click 事件監聽器。當被點選時,事件處理程式會使用 selectedOptions 獲取已選項的列表,然後遍歷列表中的選項。將構建一個字串來列出訂購的物品,並使用正確的英語語法規則(包括 牛津逗號)來構建列表。
結果
最終顯示的內容如下:
規範
| 規範 |
|---|
| HTML # dom-select-selectedoptions-dev |
瀏覽器相容性
載入中…