function addOption(select, text, value, index) {
var option = new Option(text, value);
// index 為插入位置,undefined 為附加到末尾
select.add(option, index !== undefined ? select.options[index] : null);
}
function addOptions(select, items, textKey, valueKey) {
var fragment = document.createDocumentFragment();
items.forEach(function(item) {
var text = textKey ? item[textKey] : item;
var value = valueKey ? item[valueKey] : item;
fragment.appendChild(new Option(text, value));
});
select.appendChild(fragment); // 批次寫入,單次 Reflow
}
3. 刪除選項
// 刪除全部
function clearOptions(select, keepFirst = 0) {
var len = select.options.length;
for (var i = len - 1; i >= keepFirst; i--) {
select.remove(i);
}
}
// 刪除指定值
function removeOptionByValue(select, value) {
for (var i = select.options.length - 1; i >= 0; i--) {
if (select.options[i].value === value) select.remove(i);
}
}
// 刪除選中項
function removeSelected(select) {
var idx = select.selectedIndex;
if (idx >= 0) select.remove(idx);
}
4. 取得/設定值與文字
function getSelectedValue(select) {
return select.value; // 直接取值,無選中回傳空字串
}
function getSelectedText(select) {
var idx = select.selectedIndex;
return idx >= 0 ? select.options[idx].text : '';
}
function setSelectedValue(select, value) {
select.value = value; // 不存在則 selectedIndex = -1
}
function setSelectedIndex(select, index) {
if (index >= 0 && index < select.options.length) {
select.selectedIndex = index;
}
}
5. 修改選項內容
function updateOption(select, index, newText, newValue) {
if (index >= 0 && index < select.options.length) {
var opt = select.options[index];
opt.text = newText;
opt.value = newValue !== undefined ? newValue : newText;
}
}
6. 完整互動範例:雙向編輯
<select id="editableSelect" multiple size="5"></select>
<input type="text" id="optText" placeholder="選項文字">
<input type="text" id="optValue" placeholder="選項值">
<button onclick="addOpt()">新增</button>
<button onclick="editOpt()">修改選中</button>
<button onclick="delOpt()">刪除選中</button>
<script>
var sel = document.getElementById('editableSelect');
function addOpt() {
var t = document.getElementById('optText').value;
var v = document.getElementById('optValue').value || t;
if (!t) return alert('請輸入文字');
sel.add(new Option(t, v));
document.getElementById('optText').value = '';
document.getElementById('optValue').value = '';
}
function editOpt() {
var idx = sel.selectedIndex;
if (idx < 0) return alert('請先選中項目');
var t = document.getElementById('optText').value;
var v = document.getElementById('optValue').value;
if (!t) return alert('請輸入文字');
sel.options[idx].text = t;
sel.options[idx].value = v || t;
}
function delOpt() {
var idx = sel.selectedIndex;
if (idx < 0) return alert('請先選中項目');
sel.remove(idx);
}
</script>