根據 <select> 選擇的值,動態顯示/隱藏對應的文字輸入框。常用於「其他請說明」等情境。
<select id="sel" onchange="doit()">
<option value="">請選擇</option>
<option value="0">不要輸入框</option>
<option value="1">輸入框1</option>
<option value="2">輸入框2</option>
</select>
<input id="a1" type="text" value="輸入框1" style="display:none" />
<input id="a2" type="text" value="輸入框2" style="display:none" />
<script>
function $(id) { return document.getElementById(id); }
function show(id) { $(id).style.display = 'inline'; }
function hidden(id) { $(id).style.display = 'none'; }
function doit() {
var val = $('sel').value;
hidden('a1'); hidden('a2'); // 先全部隱藏
if (val == '1') show('a1');
else if (val == '2') show('a2');
}
</script>
$() 包裝 getElementById。display: none 不佔版面空間,visibility: hidden 仍佔空間,依需求選擇。document.getElementById('sel').addEventListener('change', e => {
const val = e.target.value;
['a1','a2'].forEach(id => {
document.getElementById(id).classList.toggle('d-none', id !== 'a'+val);
});
});
搭配 CSS .d-none { display: none; } 更易維護。