不少人對javascript怎麼操做表單屬性很糾結那麼今天教你
Javascript如何操做Select和Option
//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
}