Js獲取下拉框當前選擇項的文字和值
阿新 • • 發佈:2018-11-11
現在有一個Id為AreaId的下拉框,要獲取它當前選擇項的文字和值有以下方法:
<span class="red">* </span> 地 區: <span> <select id="AreaId" name="AreaId" size="1" class="sel"> <option>-請選擇地區-</option> <option value="1">北京</option> <option value="2">上海</option> <option value="3">深圳</option> </select> </span>
方法一:使用JavaScript原生態的方法.
1.獲取值:
document.getElementById("AreaId").value;//有效,能得到正確的值.
var index=document.getElementById("AreaId").selectedIndex;//獲取當前選擇項的索引.
document.getElementById("AreaId").options[index].value;//獲取當前選擇項的值.
var obj=document.getElementById("AreaId");
for(i=0;i<obj.length;i++) {//下拉框的長度就是它的選項數.
if(obj[i].selected==true) {
var text=obj[i].value;//獲取當前選擇項的值.
}
}
2.獲取文字:
var index=document.getElementById("AreaId").selectedIndex;//獲取當前選擇項的索引.
document.getElementById("AreaId").options[index].text;//獲取當前選擇項的文字.
document.getElementById("AreaId").options[index].innerHTML;//獲取當前選擇項的文字.
var obj=document.getElementById("AreaId");
for(i=0;i<obj.length;i++) {//下拉框的長度就是它的選項數.
if(obj[i].selected==true) {
var text=obj[i].text;//獲取當前選擇項的文字.
}
}
document.getElementById("AreaId").text;//注意,這句程式碼無效,得到的結果為undefined.
方法二:使用JQuery方法(前提是已經載入了jquery庫).
1.獲取值:
$("#AreaId").val();//獲取當前選擇項的值.
var options=$("#AreaId option:selected");//獲取當前選擇項.
options.val();//獲取當前選擇項的值.
2.獲取文字:
var options=$("#AreaId option:selected");//獲取當前選擇項.
options.text();//獲取當前選擇項的文字.
options.innerHTML();//獲取當前選擇項的文字.
$("#AreaId").text;//注意,這句程式碼無效,得到的結果為undefined.
其他屬性:
innerText:
var index=document.getElementById("AreaId").selectedIndex;//獲取當前選擇項的索引.
document.getElementById("AreaId").options[index].innerText;//獲取當前選擇項的文字,IE支援,Firefox不支援.
document.getElementById("AreaId").innerHTML;//獲取當前下拉框所有的元素,包括Html程式碼.注意大小寫.
document.getElementById("AreaId").textContent;//獲取當前下拉框中所有的選擇項文字,不包括Html程式碼.