Saturday, 11 April 2015

How to define and use Enum in JavaScript

In this article I am explain how to use Enumeration in Javascript. JavaScript does not have any Enum data type but still we can create an array of key value pair and use it as Enum.
Enum_in_javascript.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript">
    var country = { "India": 1, "England": 2, "Australia": 3 };
    function DropdownChange(d) {
      switch (parseInt(d.value)) {
        case country.India:
          alert("Selected Country India");
          break;
        case country.England:
          alert("Selected Country England");
          break;
        case country.Australia:
          alert("Selected Country Australia");
          break;
      }
    }
  </script>
</head>
<body>
  <form>
  <select onchange="DropdownChange(this)">
    <option value="1">India</option>
    <option value="2">England</option>
    <option value="3">Australia</option>
  </select>
  </form>
</body>
</html>


In the above example I have created a simple enum of 3 Country India, England and Australia to which I have assigned integer values 1, 2 and 3 respectively. Now on the change of the HTML SELECT dropdown the function DropdownChange is called which based on the selected value displays the selected Country in Alert.

No comments:

Post a Comment