Cách thực hiện - Danh sách thả xuống xếp tầng
Tìm hiểu cách tạo danh sách thả xuống theo tầng bằng JavaScript.
Tạo ba danh sách thả xuống
Tạo ba danh sách thả xuống, bên trong một biểu mẫu HTML.
Danh sách thả xuống thứ hai và thứ ba sẽ hiển thị các tùy chọn khác nhau, tùy thuộc vào giá trị được chọn trong danh sách thả xuống chính.
Bước 1) Thêm HTML:
Thí dụ
<form name="form1" id="form1" action="/action_page.php">
Subjects:
<select name="subject" id="subject">
<option value=""
selected="selected">Select subject</option>
</select>
<br><br>
Topics: <select name="topic" id="topic">
<option
value="" selected="selected">Please select subject first</option>
</select>
<br><br>
Chapters: <select name="chapter" id="chapter">
<option value="" selected="selected">Please select topic first</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
Bước 2) Thêm JavaScript:
Thí dụ
var subjectObject = {
"Front-end": {
"HTML": ["Links", "Images", "Tables", "Lists"],
"CSS":
["Borders", "Margins", "Backgrounds", "Float"],
"JavaScript": ["Variables", "Operators", "Functions", "Conditions"]
},
"Back-end": {
"PHP": ["Variables",
"Strings", "Arrays"],
"SQL": ["SELECT", "UPDATE",
"DELETE"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("subject");
var topicSel
= document.getElementById("topic");
var chapterSel =
document.getElementById("chapter");
for (var x in subjectObject)
{
subjectSel.options[subjectSel.options.length] = new
Option(x, x);
}
subjectSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
chapterSel.length =
1;
topicSel.length = 1;
//display correct values
for (var y in subjectObject[this.value])
{
topicSel.options[topicSel.options.length]
= new Option(y, y);
}
}
topicSel.onchange = function() {
//empty Chapters
dropdown
chapterSel.length = 1;
//display correct values
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}
Mẹo: Đi tới Hướng dẫn CSS thả xuống của chúng tôi để tìm hiểu thêm về trình đơn thả xuống.
Mẹo: Đi tới Danh sách thả xuống có thể lưu trữ của chúng tôi để tìm hiểu thêm về danh sách thả xuống có thể lưu trữ.