[JavaScript] Creating a Dropdown Menu with forEach(), Arrow Functions, and select/option Elements
Creating a Dropdown Menu with `forEach()`, Arrow Functions, and `select`/`option` Elements in JavaScript
While building the GTPS tracker UI, one feature allows users to set or change their expectation level for a game. This is implemented as a dropdown menu built dynamically using JavaScript. Three core concepts are used together to achieve this:
* Array.forEach() for looping over options
* Arrow function syntax for defining logic concisely
* select and option DOM elements to build the dropdown
Using forEach() with Arrow Functions
In JavaScript, `forEach()` is a method available on arrays. It runs a function once for each element in the array. An arrow function can be used to define this inline:
levels.forEach((label, index) => {
// logic per item
});
- label is the value from the array (e.g., Noticed)
- index is its position (0-based)
This is equivalent to the longer version:
levels.forEach(function(label, index) {
// ...
});
Arrow functions offer cleaner syntax and work well for simple UI generation tasks.
Building a Dropdown with `select` and `option`
The dropdown UI uses two DOM elements:
- <select>: the container for the list of choices
- <option>: each individual selectable item
In JavaScript, they are created like this:
const select = document.createElement('select');
const option = document.createElement('option');
option.value = index;
option.textContent = label;
select.appendChild(option);
Each option is configured with:
- value: the internal value used in code
- textContent: what the user sees
- selected = true: marks the default selected option (if needed)
- if `true`, the current option is currently selected.
- if `false`, the current option is not selected.
Example:
if (index === currentLevel) {
option.selected = true;
}
### Putting It Together
The following snippet creates a complete dropdown menu from an array of expectation levels:
function createExpectationDropdown(currentLevel, onChangeCallback) {
const levels = ['Noticed', 'Interested', 'Looking Forward', 'Hyped', 'Must Play'];
const select = document.createElement('select');
levels.forEach((label, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = label;
if (index === currentLevel) {
option.selected = true;
}
select.appendChild(option);
});
select.onchange = (e) => {
const newLevel = parseInt(e.target.value);
onChangeCallback(newLevel);
};
return select;
}
Comments
Post a Comment