<html>
<head>
<title>添加与删除Option对象</title>
<script language="javascript">
// 添加选项
function addOption(pos){
var objSelect = document.myForm.mySelect;
// 取得字段值
var strName = document.myForm.myOptionName.value;
var strvalue = document.myForm.myOptionvalue.value;
// 建立Option对象
var objOption = new Option(strName,strvalue);
if (pos == -1 & pos > objSelect.options.length)
objSelect.options[objSelect.options.length] = objOption;
else
objSelect.add(objOption, pos);
}
// 删除选项
function deleteOption(type){
var objSelect = document.myForm.mySelect;
if (type == true)
objSelect.options[objSelect.selectedIndex] = null;
else
objSelect.remove(objSelect.selectedIndex);
}
// 显示选项信息
function showOption(objForm){
var objSelect = objForm.mySelect;
var name = objSelect.options[objSelect.selectedIndex].text;
var value = objSelect.options[objSelect.selectedIndex].value;
alert(name + " = " + value);
}
</script>
</head>
<body>
<h2>添加与删除Option对象</h2>
<hr>
<form name="myForm">
<select name="mySelect">
<option value="中国" Selected>中国</option>
<option value="日本">日本</option>
<option value="美国">美国</option>
</select>
<input type="button" onclick="showOption(this.form)" value="显示">
<input type="button" onclick="deleteOption(true)" value="删除">
<input type="button" onclick="deleteOption(false)" value="Remove方法"><br><br>
选项名称 : <input type="text" name="myOptionName" value="英国"><br>
选项的值 : <input type="text" name="myOptionvalue" value="value4">
<input type="button" onclick="addOption(-1)" value="添加">
<input type="button" onclick="addOption(0)" value="插入">
</form>
</body>
</html>