js 獲取當前select元素值的代碼
更新時間:2010年04月12日 13:49:52 作者:
對于value值可以通過select.value 取得的,但對于text值則需要通過select.options[select.sekectedIndex].txet 獲得。
1、如果 select 元素下的所有 option 元素均沒有指定 selected 屬性,會默認選中第一個。
2、可以通過 select.selectedIndex 獲取到選中的 option 元素的索引。
3、可以通過 select.options[select.selectedIndex] 獲取到選中的 option 元素。
4、option 元素 <option selected="selected" value="value3">text3</option>,可以通過 option.value 獲得 option 元素的 value 屬性值,即 value3;可以通過 option.text 獲得 option 元素內(nèi)的文本,即 text3。
5、如果 option 元素沒有定義 value 屬性,則 IE 中 option.value 無法獲得,但 Safari、Opera、FireFox 依舊可以通過 option.value 獲得,值同于 option.text 。
6、可以通過 option.attributes.value && option.attributes.value.specified 來判斷 option 元素是否定義了 value 屬性。
故,獲得當前 select 元素值的腳本如下:
var getSelectValue = funtion(select) {
var idx = select.selectedIndex,
option,
value;
if (idx > -1) {
option = select.options[idx];
value = option.attributes.value;
return (value && value.specified) ? option.value : option.text);
}
return null;
}
以前由于兼容性問題,大家用select.options[select.sekectedIndex].value來取值,不過現(xiàn)在用select.value都可以了
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
事件觸發(fā)也可以用
<select id="jb51net" onchange="alert(getSelectValue(this))">
最好是綁定事件。
2、可以通過 select.selectedIndex 獲取到選中的 option 元素的索引。
3、可以通過 select.options[select.selectedIndex] 獲取到選中的 option 元素。
4、option 元素 <option selected="selected" value="value3">text3</option>,可以通過 option.value 獲得 option 元素的 value 屬性值,即 value3;可以通過 option.text 獲得 option 元素內(nèi)的文本,即 text3。
5、如果 option 元素沒有定義 value 屬性,則 IE 中 option.value 無法獲得,但 Safari、Opera、FireFox 依舊可以通過 option.value 獲得,值同于 option.text 。
6、可以通過 option.attributes.value && option.attributes.value.specified 來判斷 option 元素是否定義了 value 屬性。
故,獲得當前 select 元素值的腳本如下:
復(fù)制代碼 代碼如下:
var getSelectValue = funtion(select) {
var idx = select.selectedIndex,
option,
value;
if (idx > -1) {
option = select.options[idx];
value = option.attributes.value;
return (value && value.specified) ? option.value : option.text);
}
return null;
}
以前由于兼容性問題,大家用select.options[select.sekectedIndex].value來取值,不過現(xiàn)在用select.value都可以了
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
事件觸發(fā)也可以用
<select id="jb51net" onchange="alert(getSelectValue(this))">
最好是綁定事件。
相關(guān)文章
鼠標移動到某個單元格上后,整個列都變色的實現(xiàn)方法
鼠標移動到某個單元格上后,整個列都變色的實現(xiàn)方法...2007-01-01javascript select控件間內(nèi)容互相移動
javascript select中內(nèi)容互相移動2009-11-11仿校內(nèi)登陸框,精美,給那些很厲害但是沒有設(shè)計天才的程序員
寫代碼對于我們來說很簡單,但是做個布局設(shè)計簡直是登天啊2008-11-11