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 brochure menu) and based on the classes contained in those options, a second drop down menu is populated based on the classes in the first.
For example selecting this option:
<option id="parRight" class="eng kor esp">Special Ed. Parents Rights</option>
Would create a second drop down I'll call the language selection drop down menu based on the classes above of "English" "Korean" and "Spanish" respectively and only those languages represented in the classes of that particular option.
So far I have been able to populate the list correctly only on the first try. My problem is that when I move on and select another brochure from the first menu my .append
method is just adding to the first language selection drop down menu.
Here is the relevant code:
HTML
<select id="docs">
<option>- Choose a document to preview -</option>
<option id="specEd" class="eng kor viet esp chin">Special Education Programs</option>
<option id="parRight" class="eng kor esp">Special Ed. Parents Rights</option>
<option id="cac" class="eng esp">CAC Brochure</option>
</select>
<div id="langs">
<ul style="display:none;">
<li>-Select a Language-</li>
<li class="eng">English</li>
<li class="esp">Español</li>
<li class="kor">한국어</li>
<li class="viet">Tiếng Việt</li>
<li class="chin">中文</li>
</ul>
</div>
jQuery
var $select = $("<select></select>");
$("#langs").append($select);
function englishTest(lang) {
return lang.hasClass("eng");
}
function spanishTest(lang) {
return lang.hasClass("esp");
}
function koreanTest(lang) {
return lang.hasClass("kor");
}
function chineseTest(lang) {
return lang.hasClass("chin");
}
function vietnameseTest(lang) {
return lang.hasClass("viet");
}
$("#docs").change(function(){
console.log("test");
var $selection = $("#docs option:selected");
if (englishTest($selection) === true) {
console.log("english passing");
$select.append("<option>English</option>");
}
if (spanishTest($selection) === true) {
console.log("spanish passing");
$select.append("<option>Español</option>")
}
if (koreanTest($selection) === true) {
console.log("korean passing");
$select.append("<option>한국어</option>")
}
if (chineseTest($selection) === true) {
console.log("chinese passing");
$select.append("<option>中文</option>")
}
if (vietnameseTest($selection) === true) {
console.log("vietnamese passing");
$select.append("<option>Tiếng Việt</option>")
}
});
I am aware that this code is repetitive and I'm not a fan of that. I'd also appreciate some pointers on how to clean this code up and make it so I'm adhering to DRY Don't Repeat Yourself coding. Thanks in advance.