Select selectedIndex 屬性
定義和用法
selectedIndex
屬性設置或返回下拉列表中被選定的選項的索引(下標)。
索引從 0 開始。
注釋:如果下拉列表允許多項選擇,它將僅返回所選第一個選項的索引。
注釋:值 "-1" 將取消選擇所有選項(如果有)。
注釋:如果未選擇任何選項,則 selectedIndex 屬性將返回 -1。
另請參閱:
HTML 參考手冊:HTML <select> 標簽
實例
例子 1
選取索引為 "2" 的 <option> 元素:
document.getElementById("mySelect").selectedIndex = "2";
例子 2
顯示下拉列表中所選選項的索引和文本:
var x = document.getElementById("mySelect").selectedIndex; var y = document.getElementById("mySelect").options; alert("Index: " + y[x].index + " is " + y[x].text);
例子 3
取消選擇所有選項:
document.getElementById("mySelect").selectedIndex = "-1";
例子 4
如果未選擇任何選項,則 selectedIndex 屬性將返回 "-1":
var x = document.getElementById("mySelect").selectedIndex;
語法
返回 selectedIndex 屬性:
selectObject.selectedIndex
設置 selectedIndex 屬性:
selectObject.selectedIndex = number
屬性值
值 | 描述 |
---|---|
number | 規定下拉列表中選定選項的索引(下標)。 |
技術細節
返回值: |
數值,表示下拉列表中所選選項的索引。索引從 0 開始。 如果未選擇任何選項,則返回值為 -1。 |
---|
瀏覽器支持
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
支持 | 支持 | 支持 | 支持 | 支持 |