萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取 DropDownList (select) 選中值與文本完整指南

前言

<select> 是表單核心控件,獲取其選中項的 value(提交值)與 text(顯示文本)是高頻操作。本文涵蓋原生 JS、jQuery、ASP.NET WebForms 控件對應的完整獲取方式。

原生 JavaScript 獲取

<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>

jQuery 獲取(推薦項目統一使用)

$(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.NET WebForms DropDownList 對應

<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 %>');

後端 C# 獲取(補充)

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) 工具函數。

copyright © 萬盛學電腦網 all rights reserved