JS操作select的方法以及JS全面学习文档
删除select中的所有OPTION
document.getElementByIdx("select的ID").options.length = 0;
为select添加一个option
document.getElementByIdx("select的ID").options.add(new Option(text,value));
移除一个指定的OPTION
document.getElementByIdx("select的ID").remove(i);
1.动态建立select
function createselect(){
var myselect = document.createelement("select");
myselect.id = "myselect";
document.body.appendchild(myselect);
}
2.添加选项option
function addoption(){
//按照id查找对象,
var obj=document.getelementbyid('myselect');
//添加一个选项
obj.add(new option("文本","值")); //这个只能在ie中有用
obj.options.add(new option("text","value")); //这个兼容ie与firefox
}
3.删除所有选项option
function removeall(){
var obj=document.getelementbyid('myselect');
obj.options.length=0;
}
4.删除一个选项option
function removeone(){
var obj=document.getelementbyid('myselect');
//index,要删除选项的序号,这里取当前选中选项的序号
var index=obj.selectedindex;
obj.options.remove(index);
}
5.获得选项option的值
var obj=document.getelementbyid('myselect');
var index=obj.selectedindex; //序号,取当前选中选项的序号
var val = obj.options[index].value;
6.获得选项option的文本
var obj=document.getelementbyid('myselect');
var index=obj.selectedindex; //序号,取当前选中选项的序号
var val = obj.options[index].text;
7.点窜选项option
var obj=document.getelementbyid('myselect');
var index=obj.selectedindex; //序号,取当前选中选项的序号
var val = obj.options[index]=new option("新文本","新值");
8.删除select
function removeselect(){
var myselect = document.getelementbyid("myselect");
myselect.parentnode.removechild(myselect);
}
整个实例的完整代码如下:
<!doctype html public "-//w3c//dtd html 4.01//zh-cn" "http://www.w3.org/tr/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html">
<head>
<script language=javascript>
function $(id)
{
return document.getelementbyid(id)
}
function show()
{
var selectobj=$("area")
var myoption=document.createelement("option")
myoption.setattribute("value","10")
myoption.appendchild(document.createtextnode("上海"))
var myoption1=document.createelement("option")
myoption1.setattribute("value","100")
myoption1.appendchild(document.createtextnode("南京"))
selectobj.appendchild(myoption)
selectobj.appendchild(myoption1)
}