Example Codes for Looping Through Enum Values (Radio Buttons)
- Enums (Enumerations): In JavaScript and TypeScript, enums provide a way to define a set of named constants. This makes your code more readable and maintainable compared to using raw numbers.
- Radio Buttons: These are UI elements where only one option can be selected at a time. They are ideal for presenting a set of mutually exclusive choices.
Looping Through Enum Values for Radio Buttons (Without Arrays):
-
Define the Enum:
enum Color { Red = "Red", Green = "Green", Blue = "Blue" }
-
Iterate Using
for...in
Loop:for (const color in Color) { if (isNaN(Number(color))) { // Ensure you're iterating over actual enum values const radioInput = document.createElement("input"); radioInput.type = "radio"; radioInput.id = `color-${color}`; // Set unique IDs radioInput.value = color; // Set value for form submission const radioLabel = document.createElement("label"); radioLabel.textContent = Color[color]; // Access enum value for display radioLabel.htmlFor = `color-${color}`; // Link label to radio button document.getElementById("radio-container").appendChild(radioInput); document.getElementById("radio-container").appendChild(radioLabel); } }
- Explanation:
- The
for...in
loop iterates over the properties of an object. However, enums in JavaScript are technically objects, so we use it here. - The
isNaN(Number(color))
check ensures we only process actual enum values (strings representing colors in this case) and not the numeric indices (often assigned by default). - We create
input
elements of type "radio" and set theirid
,value
, andname
attributes (assuming you want just one group of radio buttons). - Create
label
elements for user-friendly display, linking them to the radio buttons usinghtmlFor
. - Append the radio button and label elements to a container element (with ID "radio-container" in this example) in your HTML.
- The
- Explanation:
Additional Considerations:
- Selecting a Default Option: If you want a radio button to be selected by default, set the
checked
attribute of the corresponding radio button element. - Handling Form Submission: When the form is submitted, you can access the selected radio button's value using standard form handling techniques (e.g.,
document.querySelector('input[name="color"]:checked').value
). - Error Handling: Consider adding error handling or validation to ensure the enum is defined correctly and the container element exists in your HTML.
Key Points:
- Use
for...in
with caution as it iterates over all object properties, including inherited ones. TheisNaN
check helps filter out numeric indices. - TypeScript provides stronger type checking and enum features, which can improve code reliability.
Example Codes for Looping Through Enum Values (Radio Buttons)
JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Radio Buttons from Enum</title>
</head>
<body>
<div id="radio-container"></div>
<script>
enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
const radioContainer = document.getElementById("radio-container");
for (const color of Object.values(Color)) { // Safer iteration
const radioInput = document.createElement("input");
radioInput.type = "radio";
radioInput.id = `color-${color}`;
radioInput.value = color;
radioInput.name = "color"; // Ensure one group
const radioLabel = document.createElement("label");
radioLabel.textContent = color;
radioLabel.htmlFor = `color-${color}`;
radioContainer.appendChild(radioInput);
radioContainer.appendChild(radioLabel);
}
</script>
</body>
</html>
Explanation:
- We use
Object.values(Color)
to get an array of enum values (strings) for safer iteration. - We set the
name
attribute of the radio buttons to "color" to create a single group.
TypeScript:
enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
function createRadioButtons(container: HTMLElement, enumValues: Color[]): void {
for (const color of enumValues) {
const radioInput = document.createElement("input");
radioInput.type = "radio";
radioInput.id = `color-${color}`;
radioInput.value = color;
radioInput.name = "color"; // Ensure one group
const radioLabel = document.createElement("label");
radioLabel.textContent = color;
radioLabel.htmlFor = `color-${color}`;
container.appendChild(radioInput);
container.appendChild(radioLabel);
}
}
const radioContainer = document.getElementById("radio-container");
createRadioButtons(radioContainer, Object.values(Color)); // Pass enum values
- TypeScript offers better type safety for enums.
- The
createRadioButtons
function takes the container element and enum values as arguments, making it reusable. - We pass
Object.values(Color)
to the function to get the enum values as an array.
This method offers a concise way to iterate over both keys and values of an enum object:
// JavaScript
enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
const radioContainer = document.getElementById("radio-container");
for (const [key, value] of Object.entries(Color)) {
if (isNaN(Number(key))) { // Ensure enum value check
const radioInput = document.createElement("input");
radioInput.type = "radio";
radioInput.id = `color-${value}`;
radioInput.value = value;
radioInput.name = "color"; // Ensure one group
const radioLabel = document.createElement("label");
radioLabel.textContent = value;
radioLabel.htmlFor = `color-${value}`;
radioContainer.appendChild(radioInput);
radioContainer.appendChild(radioLabel);
}
}
// TypeScript (similar approach with type safety)
Object.entries(Color)
returns an array of key-value pairs for the enum object.- We destructure the array elements into
key
andvalue
within the loop. - The
isNaN
check remains to ensure we only process actual enum values.
Using Array Methods with TypeScript Enums:
TypeScript enums provide stronger type safety, allowing us to leverage array methods directly on the enum values:
enum Color {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
const radioContainer = document.getElementById("radio-container");
Color.values().forEach(color => {
const radioInput = document.createElement("input");
radioInput.type = "radio";
radioInput.id = `color-${color}`;
radioInput.value = color;
radioInput.name = "color"; // Ensure one group
const radioLabel = document.createElement("label");
radioLabel.textContent = color;
radioLabel.htmlFor = `color-${color}`;
radioContainer.appendChild(radioInput);
radioContainer.appendChild(radioLabel);
});
- We use
Color.values()
to get an array of enum values (strings). - The
forEach
method iterates over the array, providing each color value to the callback function.
Choosing the Right Method:
Object.entries
offers a concise way to iterate over both keys and values, useful if you need both for some reason.- Array methods with TypeScript enums provide strong type safety and a familiar syntax for array manipulation.
for...of
(previously mentioned) remains a valid option, especially in JavaScript for iterating directly over enum values (with theisNaN
check).
javascript arrays typescript