Google Apps脚本:如何从checkBoxlist中的提交功能访问数组值?

时间:2013-12-07 20:14:59

标签: javascript google-apps-script

这是一个非常基本的问题(我是GAS和JS的新手)。我有下面的代码。使用它时,我希望submit函数返回itemsSelected。但是,由于它正在返回app,我怎样才能从提交函数中获取itemsSelected值?

var fact_list = ["He planted a tree", "She visited a nursing home", "They have donated books to the library"];

function showList() {
    var mydoc = SpreadsheetApp.getActiveSpreadsheet();
    var app = UiApp.createApplication();
    var panel = app.createVerticalPanel().setId('panel');
    // Store the number of items in the array (fact_list)
    panel.add(app.createHidden('checkbox_total', fact_list.length));
    // add 1 checkbox + 1 hidden field per item 
    for(var i = 0; i < fact_list.length; i++){
      var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i]);
      var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
      panel.add(checkbox).add(hidden);
    }
    var handler = app.createServerHandler('submit').addCallbackElement(panel);
    panel.add(app.createButton('Submit', handler));
    app.add(panel);
    mydoc.show(app);
}

function submit(e){
  var numberOfItems = e.parameter.checkbox_total;
  var itemsSelected = [];
  // for each item, if it is checked / selected, add it to itemsSelected
  for(var i = 0; i < numberOfItems; i++){
    if(e.parameter['checkbox_isChecked_'+i] == 'true'){
      itemsSelected.push(e.parameter['checkbox_value_'+i]);
    }
  }
  var app = UiApp.getActiveApplication();
  app.getElementById('panel').clear().add(app.createLabel(itemsSelected));
  return app;
}

1 个答案:

答案 0 :(得分:1)

在您的示例中,函数submit(e)是由提交按钮调用的处理函数,您在该函数中定义的每个值都不可用于任何其他函数,除非您在此提交函数中创建第二个处理程序另一个事件等......(这显然不是这种情况)。

因此,将该值保留给另一个函数的唯一方法是将其存储在“某处”,以便其他函数可用。

从那里选择你的...你在评论中提到你没有使用scriptProperties,但你可以使用scriptDb或userProperties甚至是你工作的电子表格,但它必须在某个地方而且它不能在您显示的示例中的UI中,除非您在此UI中有另一个事件,它将调用我们正在讨论的第三个函数。

在这种情况下(,仅在最后一种情况下),您可以使用hidden widget或不可见textBox来指定数组的字符串化值并将其取回在使用经典e.parameter.varName的处理程序中,但这似乎不是您的用例。

希望我足够清楚...... 如果没有,请随意提及。

编辑 只是一个注释:您正在使用Label来显示itemsSelected的值。这不是最好的选择,因为Labels不能拥有名称,这意味着即使我们有一个处理程序和一个事件,我们也无法从中获得价值......标签绝对是显示价值的“一种方式”。如果它在textBox中,您可以使用某种处理程序来触发另一个函数并检索itemsSelected值。