select option设置默认选项示例

发布时间:2019-10-31编辑:脚本学堂
有关select option默认选项的设置方法,js构造select和oprtion并设置默认选项,js 构造select Option默认选中的选项不太好用,详见文中介绍。

html select构造出来默认选中的选项:
 

<option value=’beiing’ selected > 北京 </option>
 

如果是 struts 的 select:option 标签,那么有 value 可以控制默认选中的标签,方法:
 

< html:select property = "compId" styleClass = "formclass" style = "width:80%" value = "xxx " >

js 构造select Option默认选中的选项不太好用。

option源码只处理 4 个参数中的前两个: function Option( text, value , defaultSelected, selected){};
对 defaultSelected, selected 两个参数不管。
而 select 中的 selected 和 value 也不管用。
this .orderCreateModeSelect.selected = "3"; //lijg 3:auto // 不可行
this .orderCreateModeSelect.value = "3"; //lijg 3:auto // 不可行

只能用循环来处理了,方法:
 

复制代码 代码示例:
/**
params: selectUi, selectedValue
result: if the selectedValue is not single, then select the first one.
author: lijg 2009-10-10
*/
Toolkit.selectItem = function (selectUi, selectedValue) {
if (selectUi == null || selectedValue == null ) return ;
for ( var i = 0; i< selectUi.options.length; i++) {
if (selectUi.options[i].value == selectedValue) {
selectUi.options[i].selected = true ; // 可行
//this.orderCreateModeSelect.selectedIndex = i;// 可行
break ;
}
}
}

调用此方法:
 

Toolkit.selectItem( this .orderCreateModeSelect, "3" ); //set default we need