# onSelect

Description:

The `onSelect` property of the `MenuItem` object is an event handler for the event of when the menu item is selected. In other words, when the end user opens the options menu and selects a menu item either from the top-level menu list or from a submenu list, the system will fire an event and a widget can catch the event by providing a callback function.

The callback function is passed with an argument, which is an integer identifier identifying the menu item that was just selected.

It is possible to assign an individual callback function for each menu item so that the `id` argument can be ignored.

Syntax:

    MenuItem.onSelect = function(Integer id) { }

or

    MenuItem.onSelect = onMenuItemSelected;

    function onMenuItemSelected(id)
    {
      // ...
    }

Remarks:

Submenu item's callback function must be assigned to the `onSelect` property after the parent menu item is appended to the main menu pane.

For more general information on constructing an options menu, see Using softkeys.

Example code:

Creating a menu:

    window.onload = createMenu();

    // function to create a menu
    function createMenu()
    {
      // Create a Menu Object
      var optionsMenu = window.menu;

      // Set a callback function for Menu
      optionsMenu.onShow = function()
      {
         alert('Event Trigger: optionsMenu.onShow');
      }

      // Create two Menu items
      var m1 = new MenuItem('Beverages', 2001);
      var m2 = new MenuItem('Snacks', 2002);

      // Assign a callback function for the menu items
      m1.onSelect = menuEventHandler;
      m2.onSelect = menuEventHandler;

      // Append two Menu items to Menu
      optionsMenu.append(m1);
      optionsMenu.append(m2);

      // Create two more Menu items for Sub-Menu
      var m11 = new MenuItem('Coca Cola', 3001);
      var m12 = new MenuItem('Pepsi', 3002);

      // Append two Sub Menu Items to Menu 'Beverages'
      // get Menu Item reference by ID
      optionsMenu.getMenuItemById(2001).append(m11);

      // get Menu Item reference by Name
      optionsMenu.getMenuItemByName('Beverages').append(m12);

      // Assign a callback function for the submenu items
      m11.onSelect = submenuEventHandler;
      m12.onSelect = submenuEventHandler;
    }

Implement menu event handler:

    function menuEventHandler(id)
    {
      switch (id)
      {
    case 2001:
    break;
    case 2002:
    // do something
    break;
      }
    }