<select> 是表單核心控件,獲取其選中項的 value(提交值)與 text(顯示文本)是高頻操作。本文涵蓋原生 JS、jQuery、ASP.NET WebForms 控件對應的完整獲取方式。
<select id="ddlCity" onchange="showSelected(this)">
<option value="bj">北京</option>
<option value="sh" selected>上海</option>
<option value="gz">廣州</option>
</select>
<script>
function showSelected(selectEl) {
// 方法一:selectedIndex + options 集合(最通用)
var index = selectEl.selectedIndex;
var value = selectEl.options[index].value;
var text = selectEl.options[index].text;
console.log('Value:', value, 'Text:', text);
// 方法二:直接用 value 屬性(僅獲取 value)
console.log('Direct value:', selectEl.value);
// 方法三:querySelector 獲取選中 option(現代瀏覽器)
var selectedOpt = selectEl.querySelector('option:checked');
if (selectedOpt) console.log('QS value:', selectedOpt.value, 'text:', selectedOpt.text);
}
</script>
$(function() {
$('#ddlCity').change(function() {
var $this = $(this);
// 方式一:val() 直接獲取 value
var value = $this.val();
// 方式二:find selected option 獲取 text
var text = $this.find('option:selected').text();
// 方式三:獲取選中的 option 元素對象
var $opt = $this.find('option:selected');
var data = $opt.data(); // 獲取 data-* 屬性
console.log('Value:', value, 'Text:', text, 'Data:', data);
});
// 程序化設置選中項
$('#ddlCity').val('gz'); // 按 value 選中
$('#ddlCity option:contains("北京")').prop('selected', true); // 按文本模糊選中
});
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0" Text="選項一" />
<asp:ListItem Value="1" Text="選項二" />
</asp:DropDownList>
<script>
// 客戶端獲取(ClientIDMode=Static 時)
function getSelected() {
var ddl = document.getElementById('DropDownList1');
// 或 jQuery: $('#DropDownList1')
var value = ddl.value;
var text = ddl.options[ddl.selectedIndex].text;
alert('Value: ' + value + ', Text: ' + text);
}
// 若 ClientIDMode=AutoID (默認),JS 中用:
var ddl = document.getElementById('<%= DropDownList1.ClientID %>');
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) {
string value = DropDownList1.SelectedValue; // Value
string text = DropDownList1.SelectedItem.Text; // Text
int index = DropDownList1.SelectedIndex; // 索引
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 獲取 text 為空 | 用了 .value 或 .val() | 用 .text() 或 options[].text |
| 多選 select 只取第一個 | .val() 返回數組,.text() 只取第一個 | 遍歷 option:selected 獲取所有 |
| 動態新增 option 後獲取失效 | 事件綁定在舊元素 | 用事件委託 $(document).on('change', '#id', fn) |
| JSF/ASP.NET ID 帶冒號 | 命名容器生成 form:id | 用 $('#form\\:id') 或 [id$=":id"] |
// 原生
var allOptions = Array.from(select.options).map(function(opt) {
return { value: opt.value, text: opt.text, selected: opt.selected };
});
// jQuery
var allOptions = $('#ddlCity option').map(function() {
return { value: this.value, text: this.text, selected: this.selected };
}).get();
核心口訣:value 用 .value/.val(),text 用 options[selectedIndex].text/find('option:selected').text()。原生 JS 零依賴、效能最高;jQuery API 統一、鏈式友好、隱式遍歷多選。ASP.NET/JSF 開發注意客戶端 ID 生成規則。現代項目建議統一封裝 getSelectValue(id)/getSelectText(id) 工具函數。