Skip to content

Instantly share code, notes, and snippets.

@rene78
Last active May 13, 2019 17:34
Show Gist options
  • Save rene78/366315bca2250cd8ad5a007425d4f4d5 to your computer and use it in GitHub Desktop.
Save rene78/366315bca2250cd8ad5a007425d4f4d5 to your computer and use it in GitHub Desktop.
Pull down menu, where text of selected element is different than when not selected
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Select test</title>
<style>
#lang-selection {
width: 40px;
}
</style>
</head>
<body>
<select id="lang-selection" onchange="selectRecorder()"></select>
<script>
const languages = [
{ symbol: "en", fullName: "English" },
{ symbol: "de", fullName: "Deutsch" },
{ symbol: "es", fullName: "Espanol" },
{ symbol: "it", fullName: "Italiano" }
]
let previouslySelected = 0;
populateLanguageSelect();
function populateLanguageSelect() {
//fill out select
let options = "";
for (let i = 0; i < languages.length; i++) {
options += '<option value="' + languages[i].symbol + '">' + languages[i].fullName + '</option>';
}
let select = document.querySelector("#lang-selection");
select.innerHTML = options;
//now use symbol for selected language
let selectOptions = document.querySelector("#lang-selection").options;
let selected = document.querySelector("#lang-selection").selectedIndex;
selectOptions[selected].innerText = languages[selected].symbol;
// thisAndPrevSelection.push(selected);
// console.log(thisAndPrevSelection);
}
function selectRecorder() {
let selectOptions = document.querySelector("#lang-selection").options;
let selected = document.querySelector("#lang-selection").selectedIndex;
//symbol for selected
selectOptions[selected].innerText = languages[selected].symbol;
//attribute hidden to selected so it disappears from dropdown
selectOptions[selected].setAttribute("hidden", false);
//full name for previously selected
selectOptions[previouslySelected].innerText = languages[previouslySelected].fullName;
//remove "hidden" attribute from previously selected
selectOptions[previouslySelected].removeAttribute("hidden");
previouslySelected = selected;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment