寫好玩的...
思路很簡單...
html頁面上有select_main跟select_sub跟input_sub,
一開始先用css的display:none;把select_sub跟input_sub,設為不顯示,
然後利用select_main的onchange事件函式當使用者有更動選項時,
依所選的結果來決定要顯示select_sub或input_sub或都不顯示。
<!doctype html>
<html>
<head>
<style>
body{margin:0;padding:0;}
#select_sub,#input_sub{display:none;}
</style>
</head>
<body>
<form name="form1" action="" method="POST">
<select id="select_main" name="select_main">
<option value="">請選擇</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select id="select_sub" name="select_sub"></select>
<input id="input_sub" name="input_sub" value="" />
</form>
<script>
document.getElementById('select_main').onchange=function(){
var select_sub=document.getElementById('select_sub'),input_sub=document.getElementById('input_sub');
select_sub.style.display=input_sub.style.display='none';
if(this.value=='A'){
select_sub.style.display='inline-block';
select_sub.innerHTML='<option value="">請選擇</option><option value="1">1</option><option value="2">2</option><option value="3">3</option>';
}else if(this.value=='B'){
input_sub.style.display='inline-block';
}
};
</script>
</body>
</html>
html
<div class = "row mt-3">
<div class = "col-sm-2 offset-sm-4">
<select class = "form-control" id = "mySelect">
<option value = "">---</option>
<option value = "A">A</option>
<option value = "B">B</option>
<option value = "C">C</option>
</select>
</div>
<div class = "col-sm-2">
<select class = "form-control" id = "resultA">
<option value = "">---</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
<input type = "text" class = "form-control" id = "resultB">
</div>
</div>
js
const mySelect = document.getElementById('mySelect');
const resultA = document.getElementById('resultA');
const resultB = document.getElementById('resultB');
mySelect.addEventListener('change', (e) => {
switch (e.target.value) {
case 'A': {
resultA.style.display = 'block';
resultB.style.display = 'none';
break;
}
case 'B': {
resultA.style.display = 'none';
resultB.style.display = 'block';
break;
}
default: {
resultA.style.display = 'none';
resultB.style.display = 'none';
break;
}
}
});
呃
其實沒什麼好說明的
就是根據選擇的內容
秀出相對應的結果
css 隱藏的部分我就沒貼出來了