In this article I will explain with an example, how to create and use
Enums in
JavaScript.
JavaScript does not have any
Enum data type, so you need to create an array of key value pair and use it as
Enum.
HTML Markup
The HTML Markup consists of following element:
SELECT – For displaying color names.
The HTML SELECT element (DropDownList) has been assigned with a
JavaScript onchange event handler.
<select onchange="OnColourChange(this)">
<option value="0">Please select</option>
<option value="1">Red Color</option>
<option value="2">Green Color</option>
<option value="3">Blue Color</option>
</select>
Using Enums in JavaScript
Inside the
OnColourChange JavaScript function, an Array is defined.
Note: Here an Array of objects with Key Value Pairs is created which will be simulated as
Enum in
JavaScript.
Then, a SWITCH statement is executed and each case i.e. color is verified using CASE and appropriate message is displayed using
JavaScript Alert Message Box.
<script type="text/javascript">
function OnColourChange(d) {
var colors = { "Red": 1, "Green": 2, "Blue": 3 };
switch (parseInt(d.value)) {
case colors.Red:
alert("Red");
break;
case colors.Green:
alert("Green");
break;
case colors.Blue:
alert("Blue");
break;
}
}
</script>
Screenshot
Demo
Downloads