Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Creating conditional (cascading) drop-down lists using JavaScript
- * @author Kristina Marasovic
- */
- var CollegeProgram = {
- "Select a College": "college", //this is being used for select ID
- "RIT Croatia": {
- "Select a Campus": "campus", //this is being used for ID
- "Dubrovnik": {
- "Select a Program": "program",
- "Information Technology (BS)": 0,
- "International Hospitality and Service Management (BS)": 0,
- "Digital Business Minor": 0
- },
- "Zagreb": {
- "Select a Program": "program",
- "Information Technology (BS)": 0,
- "International Business (BS)": 0,
- "Service Leadership and Innovation (MS)": 0,
- "Digital Business Minor": 0
- }
- },
- "RIT": {
- "Select a Campus": "campus", //this is being used for ID
- "GCCIS - Information Sciences & Technologies": {
- "Select a Program": "program",
- "Web & Mobile Computing (BS)": 0,
- "Human Centered Computing (BS)": 0,
- "Computing & Information Technologies (BS)": 0
- },
- "GCCIS - Computer Science": {
- "Select a Program": "program",
- "Computer Science (BS)": 0,
- "Computer Science (MS)": 0
- }
- }
- };
- var selects;
- var result="";
- window.onload = resetForm;
- function resetForm () {
- selects = document.getElementById("selects");
- addSelectFor(CollegeProgram);
- };
- /**
- * Recursive building of conditional selects.
- *
- * @param {type} options data structure containing select options
- */
- function addSelectFor(options) {
- //1. stop condition
- if (Object.keys(options).length <= 1) {
- result.appendChild(document.createTextNode(output));
- //console.log("Bla: " + output);
- return;
- }
- //2. if the select element does not exist, create it
- var selectElement = document.getElementById(options[Object.keys(options)[0]]);
- if (!selects.contains(selectElement)) {
- selectElement = document.createElement('select');
- selectElement.setAttribute("id", options[Object.keys(options)[0]]); //the value of the first object property
- selects.appendChild(selectElement);
- }
- //3. clear select entries before adding new ones, use a for-in loop
- selectElement.length = 0;
- for (var key in options) {
- selectElement.options.add(new Option(key, key));
- }
- //4. implement onchange event handling - recursive call
- selectElement.onchange = function () {
- if (this.selectedIndex < 1) {
- var sibling = this.nextSibling;
- while (sibling) {
- sibling.length = 1;
- sibling = sibling.nextSibling;
- }
- return;
- }
- output += this.value + " ";
- addSelectFor(options[this.value]);
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement