在網頁裡面用
Select 是很常遇到的,之前也寫了一篇
如何利用 jQuery 動態增加 option 或取值,
jQuery 部份就不介紹了,那是需要搭配
jQuery Plugin: Select box manipulation,今天要介紹的是如何用 javascript 動態取值或者是增加 option 選項。因為我發現有使用者直接利用
innerHtml 的方式來把資料塞入到 Select 裡面,雖然
FireFox 或
Chrome 都可以正常運作,但是遇到 IE 還是沒辦法動。
如何取得 select element
底下很多方法可以取得 select element:
1. 透過 form name + element name
document.myform.selectname
2. 透過 form name + element 陣列(注意看 select 是位在 form element index 值多少)
document.myform.elements
3. 透過獨一無二的 ID
document.getElementById("selectid")
如何取得 select option 選項
透過陣列方式取得 option 選項。取第一個選項:
document.getElementById("myselect").options[0]
取第四個選項
document.getElementById("myselect").options[3]
如何取得 select option value 跟 text
直接在 option 後面接上 value 跟 text 即可
document.getElementById("myselect").options[0].value
document.getElementById("myselect").options[3].text
Select Event 介紹
onBlur: 假設目前 focus 在 select 上時,如果下一步移開到另一個 element 的時候將會觸發
onChange: 用於選單選項改變時,會觸發條件,底下看個簡單例子
首先我們可以看到程式碼
selectmenu.onchange,也就是選擇其他選項時候將會觸發,透過
this.selectedIndex 你選擇的 index 來取 value 值。
onFocus: 如果 focus 在 Select element 時,將會觸發
Select Property 介紹
disabled: 設定 Boolean value 用來控制 select 是否 disabled。
length: 計算有多少個 options
document.getElementById("mymenu").length
selectedIndex: 用來取得目前 options 陣列索引值 index,假如沒有選任何選項則回傳 -1,底下範例:
type: select 提供兩種 type: select-one 跟 select-multiple,我們可以針對 form 裡面所有的 element 來找出屬於 select 選單,底下範例:
Select Methods 介紹
add(newoption, beforeoption*): 用來動態增加 option,不多說底下先來看一個範例
從上面程式,大家可以看到透過 new Option("text", "value") 來動態新增 option,至於 add 的第二個參數是設定要增加到哪個 option 後面,IE 瀏覽器必須用 integer 來帶入,其他瀏覽器都需要 object reference。
*Important: beforeoption should be an object reference to an option except in IE, where it must be an integer representing the index of the option instead.
remove(optionindex): 移除 option,只要知道 index 即可刪除,看底下範例
var myselect=document.getElementById("sample")
myselect.remove(myselect.length-1) //removes last option within SELECT
上面範例是移除最後一個 option
Select Option object 介紹
index: 回傳該 option index 值
selected: 判斷是否選擇了該 option,直接看範例:
text: option 指定說明
value: option 指定值
如何取代既有的 option
只要針對該 option index 重新指定 new Option 即可,底下範例:
var myselect=document.getElementById("sample")
myselect.options[0]=new Option("New 1st option", "who") //replace 1st option with a new one
myselect.options[myselect.length]=new Option("Brand new option", "what") //add a new option to the end of SELECT
上面全部的範例皆來自
JavaScript Reference Select 網站
Related