獲取 <select> 當前選中項的 value 與顯示文本是表單處理的基礎操作。本文匯總原生 JS、jQuery 多種寫法,並說明多選下拉框的處理差異。
<select id="city" name="city">
<option value="bj">北京</option>
<option value="sh" selected>上海</option>
<option value="gz">廣州</option>
</select>
var sel = document.getElementById('city');
// 方式一:selectedIndex(最標準)
var value = sel.options[sel.selectedIndex].value; // "sh"
var text = sel.options[sel.selectedIndex].text; // "上海"
// 方式二:value 屬性直接取值(不需索引)
var value2 = sel.value; // "sh" — 直接返回當前選中 option 的 value
// 但無法直接獲取 text,仍需用 selectedIndex
multiplevar selMulti = document.getElementById('cityMulti'); //
var $sel = $('#city');
var value = $sel.val(); // "sh" — 推薦
var text = $sel.find('option:selected').text(); // "上海"
var text2 = $sel.children('option:selected').text(); // 同樣有效
// 兼容寫法(針對極舊版本)
var text3 = $sel[0].options[$sel[0].selectedIndex].text;
var values = $('#cityMulti').val(); // 返回數組 ["bj", "gz"],jQuery 自動處理 multiple
var texts = $('#cityMulti option:selected').map(function () {
return $(this).text();
}).get(); // ["北京", "廣州"]
// 原生
sel.value = 'gz'; // 直接設置 value,瀏覽器自動匹配 option
// jQuery
$('#city').val('gz'); // 同樣設置 value
// 或設置 selected 屬性
$('#city option[value="gz"]').prop('selected', true);
select.text 返回所有 option 文本拼接,非當前選中項 —— 切勿使用。option.selected 屬性為布爾值,設置時用 true/false,非字符串 "selected"。<option> 後,selectedIndex 可能不更新,建議用 value 設置。.val() 在多選時返回數組,單選時返回字符串,類型不一致需注意判斷。function getSelectSelected(selectId) {
var el = document.getElementById(selectId);
if (!el) return null;
if (el.multiple) {
var vals = [], txts = [];
for (var i = 0; i < el.options.length; i++) {
var o = el.options[i];
if (o.selected) { vals.push(o.value); txts.push(o.text); }
}
return { values: vals, texts: txts };
} else {
var idx = el.selectedIndex;
return idx >= 0 ? { value: el.options[idx].value, text: el.options[idx].text } : null;
}
}
掌握原生與 jQuery 兩套 API,根據項目依賴靈活選擇,代碼更簡潔健壯。