How to create: Cascading dropdown lists
- Pagina precedente Fare clic sul menu a discesa
- Pagina successiva Menu a discesa nella barra di navigazione superiore
Learn how to use JavaScript to create cascading dropdown lists.
Create three dropdown lists
Create three dropdown lists within the HTML form.
The second and third dropdown lists will display different options depending on the value selected in the parent dropdown list.
First step - Add HTML:
<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>
Second step - Add JavaScript:
var subjectObject = { "Front-end": { "HTML": ["Links", "Images", "Tables", "Lists"], "CSS": ["Bordi", "Margine", "Sfondo", "Flottante"] "JavaScript": ["Variabili", "Operatori", "Funzioni", "Condizioni"] }, "Back-end": { "PHP": ["Variabili", "Stringhe", "Vettori"], "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() { // Svuota i menu a discesa "Capitoli" e "Argomenti" chapterSel.length = 1; topicSel.length = 1; // Visualizza il valore corretto for (var y in subjectObject[this.value]) { topicSel.options[topicSel.options.length] = new Option(y, y); } } topicSel.onchange = function() { // Svuota il menu a discesa "Capitoli" chapterSel.length = 1; // Visualizza il valore corretto 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]); } } }
Pagina relativa
Tutorial:Menu a discesa CSS
Tutorial:Come creare un menu a discesa hover
- Pagina precedente Fare clic sul menu a discesa
- Pagina successiva Menu a discesa nella barra di navigazione superiore