Search code examples
titaniumappceleratortitanium-mobile

cant able to get selected option from OptionDialog box in Titanium Appcelerator?


I have created a OptionDialog in Titanium. I have added those option list from a dynamic array. how to get the particular option value on clicking any item from dialog box?

var View = Ti.UI.createTextField({
height : '60dp',
width : '90%',
value : 'click here'
)};

myArray = ['Lion','Tiger','Cat','Elephant','Dog'];

var opts = {
  cancel: 2,
  options: myArray,
  selectedIndex: 2,
  destructive: 0,
};

var dialog;
View.addEventListener('click',function(){
    dialog = Ti.UI.createOptionDialog(opts).show();
});

I have tried like below,which doesn't work.

dialog.addEventListener('click',function(e){
    alert('You Clicked' + e.source.options);
});

Solution

  • Change your code as follows

    var myArray = ['Lion','Tiger','Cat','Elephant','Dog'];
    
    var opts = {
      cancel: 2,
      options: myArray,
      selectedIndex: 2,
      destructive: 0,
    };
    
    var dialog;
    View.addEventListener('click',function(){
        dialog = Ti.UI.createOptionDialog(opts);
        dialog.show();
        dialog.addEventListener('click', onSelectDialog);
    });
    
    function onSelectDialog(event){
        var selectedIndex = event.source.selectedIndex;
        //OR
        //var selectedIndex = dialog.selectedIndex();
        alert('You have selected' + myArray[selectedIndex ]);
    }
    

    Hope it helped you