Miscellaneous‎ > ‎

Moving item from one listBox to another - Google Apps Script

Problem Summary
Move item from first listBox to second listBox just by clicking the item in first listBox.
References
Example Demo:
To try the demo, click on the items in the left hand side listbox (source). Once you click an Item, it will be moved to the Right hand side list box (destination) and that item will be removed from source list box.
 
 


Example Code:
function doGet(){
  
var app = UiApp.createApplication().setTitle('Test');
  
var panel = app.createHorizontalPanel();
  
var lb1 = app.createListBox(true).setId('lb1').setName('lb1').setSize('200', '200');
  
var itemArray = ['ITem1','ITem2','ITem3','ITem4','ITem5','ITem6','ITem7','ITem8','ITem9','ITem10','ITem11','ITem12'];
  
for(var i=0; i<itemArray.length; i++){
    lb1
.addItem(app.createLabel(itemArray[i])).setItemText(i, itemArray[i]);
  
}
  
var serializedItemArray = Utilities.jsonStringify(itemArray);
  
var hidden = app.createHidden().setName('updatedItemArray').setId('updatedItemArray').setValue(serializedItemArray);
  
var lb2 = app.createListBox(true).setId('lb2').setName('lb2').setSize('200', '200');
  
var handler = app.createServerHandler('_move');
  handler
.addCallbackElement(panel);
  lb1
.addClickHandler(handler);  
  panel
.add(lb1).add(lb2).add(hidden);
  app
.add(panel);
  
return app;
}


function _move(e){
  
var app = UiApp.getActiveApplication();
  
//Get the Instances of different UI elements
  
var lb1 = app.getElementById('lb1');
  
var lb2 = app.getElementById('lb2');
  
var hidden = app.getElementById('updatedItemArray');
  
  
//Get the selected item value
  
var selectedItem = e.parameter.lb1;
  
Logger.log(selectedItem);
  
//Get the old item array from hidden elelemnt
  
var ItemArray = Utilities.jsonParse(e.parameter.updatedItemArray);
  
if(ItemArray.length > 0 && selectedItem != ''){
    
//Get the index of selected item in old Item array
    
var index = ItemArray.indexOf(selectedItem);
    
//Remove item from lb1
    lb1
.removeItem(index);
    
//Add item in lb2
    lb2
.addItem(selectedItem);
    
//remove the selected item from array
    
ItemArray.splice(index,1);
    
var serializedNewItemArray = Utilities.jsonStringify(ItemArray);
    
//Update the hidden item value with new serialized array
    hidden
.setValue(serializedNewItemArray);
  
}
  
return app;
}

Comments