編輯注意底部。如何創建一組依賴選擇列表,其中連續列表取決於前面列表選擇的選擇?
我所希望做的是創建一個腳本,讓我查看在select
元素選定的選項,並使用該選擇作爲一個限制器,以什麼第二select
元素選項可以使用。
儘管該示例顯示了我正在討論的內容的一個非常簡單的說明,但實際上我將使用代碼來限制較大選項列表的選項。在更大的代碼,我想option_1_1
從selectElement2
通過options_2_9
限制選項options_2_1
,option_1_2
通過option_2_11
限制了選擇到option_2_1
,並option_1_3
通過option_2_5
限制選擇,option_2_1
。
作爲一個例子;
<!DOCTYPE html>
<html>
<head>
<!-- I prefer not to use PHP, but if that's the ONLY way to do it, say so. -->
<script>
/* Need script to perform */
</script>
</head>
<body>
<!-- Select element 1 -->
<select id="selectElement1">
<!-- If option_1_0 is selected, no options are available in selectElement2 -->
<option id="option_1_0" value="" selected></option>
<!-- If option_1_1 is selected, only select options are available in selectElement2 -->
<option id="option_1_1" value="1" >1</option>
<!-- If option_1_2 is selected, only select options are available in selectElement2 -->
<option id="option_1_2" value="2" >2</option>
<!-- If option_1_3 is selected, only select options are available in selectElement2 -->
<option id="option_1_3" value="3" >3</option>
</select>
<!-- Select element 2 -->
<select id="selectElement2">
<!-- Selected by default and cannot change unless a choice is selected from selectElement1 -->
<option id="option_2_0" value="" selected></option>
<!-- If option_1_1 is selected, only option_2_1 is available -->
<option id="option_2_1" value="1">1</option>
<!-- If option_1_2 is selected, only option_2_1 and option_2_2 are available -->
<option id="option_2_2" value="2" >2</option>
<!-- If option_1_3 is selected, only option_2_3 is available -->
<option id="option_2_3" value="3" >3</option>
<!-- If option_1_3 is selected, only option_2_3 and option_2_4 are available -->
<option id="option_2_4" value="4" >4</option>
</select>
</body>
</html>
編輯 謝謝大家。你們都幫助了我很多。這是最後的工作代碼:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
var gradeValue = {};
gradeValue['A'] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
gradeValue['B'] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];
gradeValue['C'] = ['1', '2', '3', '4', '5'];
function changeList() {
var gradeList = document.getElementById("grade");
var rankingList = document.getElementById("ranking");
var selGrade = gradeList.options[gradeList.selectedIndex].value;
while (rankingList.options.length) {
rankingList.remove(0);
}
var rank = gradeValue[selGrade];
if (rank) {
for (var i = 0; i < rank.length; i++) {
var ranks = new Option(rank[i], i);
rankingList.options.add(ranks);
}
}
}
</script>
</head>
<body>
<select id="grade" onchange="changeList()">
<option value="">-- Select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select id="ranking"></select>
</body>
</html>