<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>動(dòng)態(tài)添加option</title>
</head>
<body>
<select id="mySel">
<option value="1">option-1</option>
<option value="2">option-2</option>
<option value="3">option-3</option>
</select>
新增列表項(xiàng)值:<input type="text" id="val"/>
內(nèi)容:<input type="text" id="txt"/>
<input type='button' value='添加' onclick="inserItem()"/>
<script type="text/javascript">
function inserItem(){
var val = document.getElementById("val").value;
var txt = document.getElementById("txt").value;
var sel = document.getElementById("mySel");
var option = new Option(txt, val);
sel.options.add(option);
}
function getvalue(obj) {
var m=obj.options[obj.selectedIndex].value
var n=obj.options[obj.selectedIndex].text
alert(m);//獲取value
alert(n);//獲取文本
}
/*
Native way:
var mySel = document.getElementById("mySel");
mySel.options.length=0; //動(dòng)態(tài)刪除select中的所有options
mySel.options.remove(indx); //動(dòng)態(tài)刪除select中的某一項(xiàng)option:
mySel.options.add(new Option(text,value)); //動(dòng)態(tài)添加select中的項(xiàng)option
var m = mySel.options[indx].value(or .text) //獲取文本/value
if (mySel.selectedIndex > - 1 ) { //檢測(cè)是否有選中
mySel.options[mySel.selectedIndex] = null ; //刪除被選中的項(xiàng)
mySel.options[mySel.selectedIndex] = new Option( " 你好 " , " hello " ); //修改所選擇中的項(xiàng)jQuery way:
$(document).on("change","#mySel",function(){
alert('value:'+$(this).val());//獲取value
alert('text:'+$(this).find("option:selected").text());//獲取選中文本
});
$("#mySel").append("<option value='n+1'>第N+1項(xiàng)</option>"); //添加一個(gè)option
$("#mySel option:selected").text(); //獲取選中的內(nèi)容
$("#mySel option:selected").attr("id"); //獲取選中的的option的id值
$('#mySel option:selected').remove(); //添除選中項(xiàng)
$("#mySel option:eq(1)").remove(); // 刪除第2個(gè)元素
$('#mySel option[value=5]').remove();
$('#mySel option:first').val(); // 獲取第1個(gè)option的值
$("#mySel").attr('value' , $('#test option').eq($('#test option').length - 1).val());
$("#mySel option:selected").attr("data-xx", "---");
$("#mySel").find("option:selected").atrr("自定義屬性")
var selectId = $('#mySel>option:selected');
$(":selected").length //為選擇的個(gè)數(shù)蒙具,
$("select option").size() //為所有選項(xiàng)的個(gè)數(shù)
*/
</script>
</body>
</html>