萬盛學電腦網

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

JavaScript 自動查找 Select 下拉選項並選中指定文本

核心函數

function findSelect(name) {
    var select = document.getElementsByName(name)[0];
    if (!select) return;
    
    var keyword = document.getElementById('to_find_str').value;
    if (!keyword) return;
    
    var options = select.options; // HTMLOptionsCollection
    var found = false;
    
    for (var i = 0; i < options.length; i++) {
        if (options[i].text.indexOf(keyword) !== -1) {
            options[i].selected = true;
            select.value = options[i].value; // 觸發 change 事件
            if (select.onchange) select.onchange(options[i].value);
            found = true;
            break;
        }
    }
    
    if (!found) alert('已沒有匹配內容');
}

HTML 結構

<select name="Activity[Identifier]" id="Identifier" onchange="change_activity(this.value)">
    <option value="">請選擇</option>
    <option value="ACT001">活動類型一</option>
    <option value="ACT002">活動類型二</option>
    <option value="ACT003">特殊活動三</option>
</select>

<input type="text" id="to_find_str" placeholder="輸入關鍵字" />
<input type="button" value="查找並選中" onclick="findSelect('Activity[Identifier]')" />

關鍵點解析

  • select.options 直接訪問選項集合,比 childNodes 更語義化
  • option.text 獲取顯示文本,option.value 獲取提交值
  • 設置 select.value 可觸發原生 change 事件(部分瀏覽器需手動觸發)
  • 手動調用 select.onchange() 確保業務邏輯執行

現代增強版

function fuzzySelect(selectId, keyword) {
    const select = document.getElementById(selectId);
    const opt = [...select.options].find(o => o.text.includes(keyword));
    if (opt) {
        opt.selected = true;
        select.dispatchEvent(new Event('change', {bubbles: true}));
    } else {
        console.warn('未匹配:', keyword);
    }
}

// 防抖搜索輸入框
$('#to_find_str').on('input', _.debounce(function() {
    fuzzySelect('Identifier', this.value);
}, 300));

支持模糊匹配、防抖輸入、標準事件分發,體驗更佳。

copyright © 萬盛學電腦網 all rights reserved