Dynamic Drop Down Menus Using Jquery For Website
Hello everyone I need some help making a drop down menu that is reactive to classes contained in a set of options. What I want to do is have users select brochures (I'll call the b
Solution 1:
In my code when you click on the drop down another drop down is created from the classes form the original options. I made a map of classes to languages that will be used to output the options in the new dropdown. I hope you understand. If you have any questions let me know.
$(function(){
var map = {
"eng" : "English",
"esp" : "Español",
"kor" : "한국어",
"viet" : "Tiếng Việt",
"chin" : "中文"
}
$("#docs").on("change", function(){
//explanation of .attr()// lets say your html looks like this === //<option id="specEd" class="eng kor viet esp chin">Special Education Programs</option> // .attr("class") will create a string of all the classes like : 'eng kor viet esp chin'var selected = $("option:selected", this).attr("class");
//then you split the string by spaces to get an arr like ["eng", "kor", "viet", "esp", "chin"]var arr = selected.split(" ");
console.log(arr) //["eng", "kor", "viet", "esp", "chin"]//Next, remove the old dropdown that was appended. If `.added` was not there it will remove nothing//Then after it is removed append the new dropdown//so, on every change event you're removing the old and appending the new.
$(".added").remove()
$("body").append("<select class='added'>")
//since the string of classes are split into an array you can use the array method of [forEach][1]
arr.forEach(function(e){
//`e` is each element in `arr`
$(".added").append("<option>"+map[e]+"</option>");
// so map[eng] == "English" then it goes to map[kor] etc..// you should know how JavaScript objects work
})
})
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><selectid="docs"><option>- Choose a document to preview -</option><optionid="specEd"class="eng kor viet esp chin">Special Education Programs</option><optionid="parRight"class="eng kor esp">Special Ed. Parents Rights</option><optionid="cac"class="eng esp">CAC Brochure</option></select>
Solution 2:
For the DRY coding, I would suggest replacing these functions
functionenglishTest(lang) {
return lang.hasClass("eng");
}
With something like this
functiontestLanguage(selection, lang) {
return selection.hasClass(lang);
}
And then calling it like
testLanguage($selection, "eng") === true
For your main question, you seem to be appending stuff always when the selection changes, but you never clear anything.
Post a Comment for "Dynamic Drop Down Menus Using Jquery For Website"