<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select控制元件測試</title>
</head>
<body>
<select id="mySel">
</select>
<input type="text" id="id" placeholder="請輸入要移除的ID號碼">
<hr/>
<button id="btn1" type="button" >初始化資料</button>
<button id="btn2" type="button" >測試移除操作</button>
<button id="btn3" type="button" >測試移除選中的專案</button>
<button id="btn4" type="button" >修改選中專案的顯示名稱</button>
<button id="btn5" type="button" >設定1002選擇狀態</button>
<button id="btn6" type="button" >獲取當前專案的文字,屬性,索引</button>
<button id="btn7" type="button" >清空列表</button>
<script type="text/javascript">
window.onload=function () {
var objSelect = document.getElementById("mySel");
document.getElementById("btn1").onclick=function () {
var length = objSelect.options.length;
if(length==0){
alert("沒有內容,新增預設內容");
objSelect.innerHTML="<option value=''>請選擇你的部門</option>";
this.disabled=false;
}else{
this.disabled=true;
var valItem = new Option("測試部","1001");
objSelect.options.add(valItem);
var valItem = new Option("軟體部","1002");
objSelect.options.add(valItem);
var valItem = new Option("研發部","1003");
objSelect.options.add(valItem);
}
}
document.getElementById("btn2").onclick=function () {
var id = document.getElementById("id").value;
var length = objSelect.options.length;
if(length>0){
for(var i = 0 ;i<length;i++){
if(objSelect.options[i].value==id){
objSelect.options.remove(i);
break;
}
}
}else{
alert("沒有專案,空白的!");
document.getElementById("btn1").disabled=false;
}
}
document.getElementById("btn3").onclick=function () {
var length = objSelect.options.length;
for(var i = 0 ;i<length;i++){
if(objSelect.options[i].selected){
objSelect.options[i]=null;
break;
}
}
}
document.getElementById("btn4").onclick=function () {
var oValue = 1001;
var modText = "修改為胖先森";
var modValue = 101;
var length = objSelect.options.length;
for(var i = 0 ;i<length;i++){
if(objSelect.options[i].value==oValue){
objSelect.options[i].text=modText;
objSelect.options[i].value=modValue;
break;
}
}
}
document.getElementById("btn5").onclick=function () {
objSelect.value=1002;
}
document.getElementById("btn6").onclick=function () {
alert("當前的索引:"+objSelect.selectedIndex);
alert("當前的文字:"+objSelect.options[objSelect.selectedIndex].text);
alert("當前值,方式一:"+objSelect.options[objSelect.selectedIndex].value);
alert("當前值,推薦方式二:"+objSelect.value);
}
document.getElementById("btn7").onclick=function () {
objSelect.options.length=0;
document.getElementById("btn1").disabled=false;
}
}
</script>
</body>
</html>
複製程式碼