<html>
<head><title>獲取下拉列表選中項(xiàng)的值和文本(select)</title></head>
<body>
<script>
//獲取下拉列表選中項(xiàng)的文本
function getSelectedText(name){
var obj=document.getElementById(name);
for(i=0;i<obj.length;i++){
if(obj[i].selected==true){
return obj[i].innerText; //關(guān)鍵是通過(guò)option對(duì)象的innerText屬性獲取到選項(xiàng)文本
}
}
}
//獲取下拉列表選中項(xiàng)的值
function getSelectedValue(name){
var obj=document.getElementById(name);
return obj.value; //直接用其對(duì)象的value屬性便可獲取到
}
</script>
<select id="myselect">
<option value="fist">1</option>
<option value="second">2</option>
<option value="third">3</option>
</select>
<input type="button" value="所選文本" onclick="alert(getSelectedText('myselect'));" />
<input type="button" value="所選值" onclick="alert( getSelectedValue('myselect'));" />
</body>
</html>
Jquery寫(xiě)法
<html> <head>
<title>獲取下拉列表選中項(xiàng)的值和文本(select)</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
function getValue(elem){
alert($(elem).val());
}
function getText(elem){
$(elem).children().each(function(){
if($(this).attr("selected")===true){
alert($(this).text());
}
});
}
</script>
</head>
<body>
<select id="myselect">
<option value="fist">1</option>
<option value="second">2</option>
<option value="third">3</option>
</select>
<input type="button" value="所選文本" onclick="getValue('#myselect')" />
<input type="button" value="所選值" onclick="getText('#myselect')" />
</body>
</html>
該文章在 2012/5/9 18:23:57 編輯過(guò)