js 获取select对象

JavaScript074

js 获取select对象,第1张

1、获取选中select的value和text,html代码如下:

<select id="mySelect">

<option value="1">one</option>

<option value="2">two</option>

<option value="3">three</option>

</select>

则可通过以下script代码s来获取选中的value和text

$("#mySelect").val()//获取选中记录的value值

$("#mySelect option:selected").text()//获取选中记录的text值

2、运用new Option("文本","值")方法添加选项option

var obj = document.getElementById("mySelect")

obj.add(new Option("4","4"))

3、删除所有选项option

var obj = document.getElementById("mySelect")

obj.options.length = 0

4、删除选中选项option

var obj = document.getElementById("mySelect")

var index = obj.selectedIndex

obj.options.remove(index)

5、修改选中选项option

var obj = document.getElementById("mySelect")

var index = obj.selectedIndex

obj.options[index] = new Option("three",3) //更改对应的值

obj.options[index].selected = true //保持选中状态

6、删除select

var obj = document.getElementById("mySelect")

obj.parentNode.removeChild(obj)//移除当前对象

7、select选择的响应事件

$("#mySelect").change(function(){

//添加所需要执行的操作代码

})

<script type="text/javascript">

function addList(){

var list = document.getElementById("list")

var bb=["javascript1","javascript2","javascript3","javascript4"]

for(var i = 0i <bb.lengthi++){

var newOption = document.createElement("option")

newOption.setAttribute("value", i)

newOption.appendChild(document.createTextNode(bb[i]))

list.appendChild(newOption)

}

}

function clearList(){

var list = document.getElementById("list")

for(var i = list.options.lengthi >= 0i--){

list.remove(i)

}

}

</script>

</head>

<body>

<select name="list" id="list" style="width:120px">

</select>

<input type="button" onclick="addList()" value="生成"/>

<input type="button" onclick="clearList()" value="清空" />

</body>