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('已沒有匹配內容');
}
<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));
支持模糊匹配、防抖輸入、標準事件分發,體驗更佳。