javascript select option 操作详解
1 检测是否有选中
if(objSelect.selectedIndex > -1) {
//说明选中
} else {
//说明没有选中
}
2.动态创建select
function createSelect(){
var mySelect = document.createElement_x("select");
mySelect.id = "mySelect";
document.body.appendChild(mySelect);
}
3.添加选项option
function addOption(){
//根据id查找对象,
var obj=document.getElementByIdx('mySelect');
//添加一个选项
obj.add(new Option("文本","值"));
}
4.删除所有选项option
function removeAll(){
var obj=document.getElementByIdx('mySelect');
obj.options.length=0;
}
5.删除一个选项option
function removeOne(){
var obj=document.getElementByIdx('mySelect');
//index,要删除选项的序号,这里取当前选中选项的序号
var index=obj.selectedIndex;
obj.options.remove(index);
}
6.获得选项option的值
var obj=document.getElementByIdx('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[index].value;
7.获得选项option的文本
var obj=document.getElementByIdx('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[index].text;
8.修改选项option
var obj=document.getElementByIdx('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[index]=new Option("新文本","新值");
9.删除select
function removeSelect(){
var mySelect = document.getElementByIdx("mySelect");
mySelect.parentNode.removeChild(mySelect);
}
javascript select option对象
一、基础理解:
var e = document.getElementByIdx("selectId");
e.options = new Option("文本", "值");
1、options数组的属性:
length -------长度属性
selectedIndex ------ 当前被选中的文本的索引值,此索引值是内存自动分配的(0,1,2,3....)对应(第一个文本值,第二个文本值,第三个文本值,第四个文本值.......)
2、单个option的属性(即obj.options[obj.selectedIndex]是指定的某个<option>标签):
text ===== 返回/指定文本
value =====返回/指定文本,与<option value="...">一致
index ======返回下标
selected======返回/指定该对象是否被选中,指定true or false可动态改变选中项
defaultSelected =====返回该对象默认是否被选中,true/false
3、option的方法:
增加一个<option>标签======obj.options.add(new("文本", "值"))
删除一个<option>标签======obj.options.remove(obj.selectedIndex);
获取一个<option>标签======obj.options[obj.selectedIndex].text ;
修改一个<option>标签======obj.options[obj.selectedIndex] = new Option("新文本", "值") ;
删除所有<option>标签======obj.options.length = 0 ;
获取一个<option>标签的值====obj.options[obj.selectedIndex].value ;
注意:
obj.option中的option不需要大写
new Option中的option需要大写
二、示例:
<html>
<head>
<script language="javascript">
function chk(){
var obj = document.getElementByIdx("mySelect");
}
</script>
</head>
<body>
<select id="mySelect">
</select>
<input type="button" name="button" value="查看结果" οnclick="javascript:chk();">
</body>
</html>