How to get the index of the selected item in a lis

2019-05-18 07:37发布

问题:

I want to get the index of the selected item in a Google Apps Script list box not the selected item itself. All of the examples I've seen so far create a server handler that gets the value of the list box through

var list1Value = e.parameter.list1;

I want to get the index though so I can index into an array. I tried to use this solution http://productforums.google.com/forum/#!category-topic/apps-script/services/vXa57-9T6E4 but my script complained that indexOf wasn't recognized

var currentmonth = months.indexOf(e.parameter.list1);

Anyone have a good idea on how to get the index? By the way this is a google apps script running in Sites not in Spreadsheets if that makes a difference.

回答1:

The other answer doesn't make much sense since Google Apps Script is executed on Google's server, not in your browser and indexOf() is well recognized in GAS.

You should use an array with the elements of you listBox and then using listArray.indexOf(listelement); you'll get the index of the selected item.

example :

//in the UI construction 

var ItemlistArray = ['item1','item2','item3','item4'];// note that this variable definition could be placed outside of the function so it becomes a global variable...
for (n=0,n<ItemlistArray.length;++n){
ListBox.addItem(ItemlistArray[n]
}

//in the Handler function

var item = e.parameter.listBoxName
var ItemlistArray = ['item1','item2','item3','item4'];// if ItemlistArray is global this line can be removed
var index = ItemlistArray.indexOf(item); // if for example the selected item was 'item3', index will be 2