国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jscript > JS 如何获取当前 select 元素的值

JS 如何获取当前 select 元素的值

来源:程序员人生   发布时间:2014-04-24 13:51:38 阅读次数:2879次

如果 select 元素下的所有 option 元素均没有指定 selected 属性,会默认选中第一个。

可以通过 select.selectedIndex 获取到选中的 option 元素的索引。

可以通过 select.options[select.selectedIndex] 获取到选中的 option 元素。

option 元素 text3,可以通过 option.value 获得 option 元素的 value 属性值,即 value3;可以通过 option.text 获得 option 元素内的文本,即 text3。

如果 option 元素没有定义 value 属性,则 IE 中 option.value 无法获得,但 Safari、Opera、FireFox 依旧可以通过 option.value 获得,值同于 option.text 。

可以通过 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;
}

原文:http://www.planabc.net/2010/03/27/how_to_get_select_element_value/

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生