js中怎么获取option的值

JavaScript06

js中怎么获取option的值,第1张

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

</head>

<body>

<select id="sel" onchange="cge()">

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

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

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

</select>

</body>

<script>

function cge(){

var sel=document.getElementById('sel')

                var sid=sel.selectedIndex

alert(sel[sid].value+'-'+sel[sid].innerHTML)

}

</script>

</html>

jq的话就一句

$("#sel option:selected").text()

$("#sel option:selected").val()

现在有一id=test的下拉框,怎么拿到选中的那个值呢?

分别使用javascript原生的方法和jquery方法

<select id="test"  name="">   

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

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

 </select>

code:

一:javascript原生的方法

  1:拿到select对象: var  myselect=document.getElementById("test")

  2:拿到选中项的索引:var index=myselect.selectedIndex              // selectedIndex代表的是你所选中项的index

  3:拿到选中项options的value:  myselect.options[index].value

  4:拿到选中项options的text:  myselect.options[index].text

二:jquery方法(前提是已经加载了jquery库)

1:var options=$("#test option:selected")  //获取选中的项

2:alert(options.val())   //拿到选中项的值

3:alert(options.text())   //拿到选中项的文本

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

<select id="sel">

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

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

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

</select>

</body>

</html>

<script type="text/javascript">

var sel=document.getElementById("sel") //获取select

var op=sel.children // 获取所有的option

alert(op[0].value) //弹出option的第一个value值;

alert(op[1].value) //弹出option的第二个value值;

alert(op[3].value) //弹出option的第三个value值;

</script>