js和jq获取下来列表选中项的值和文本

来源:互联网 发布:手机事件提醒软件 编辑:程序博客网 时间:2024/05/23 19:15

转自:http://www.111cn.net/wy/jquery/45372.htm。

js取值

//获取下拉列表选中项的值

function getSelectedValue(name){
var obj=document.getElementById(name);
return obj.value;      //如此简单,直接用其对象的value属性便可获取到
}

//获取文本值

1.

<select Id="select">
 <option>1</option>
  <option selected="selected">2</option>
  <option>3</option>
</select>

<script language="javascript" type="text/javascript">
var ById = document.getElementById("Select")
alert(ById.options[ById.selectedIndex].text)
</script>

2.

<select id="select1" onChange="abc()"> 
<option value="1">看书</option>
<option value="2">体育</option>
</select>
<script type="text/javascript">
function abc(){
var obj =document.getElementById("select1");
alert(obj.options[obj.selectedIndex].text);
}
</script>

jquery

获取文本

$("#select option[selected]").text();

//select和option之间有空格,option为select的子元素 

$("#select option:selected").text();

获取值

$("#select").val();//取值   
$("#select").val("value");//设置,如果select中有值为value的选项,该选项就会被选中,如果不存在,则select不做

0 0