无法在Google Apps脚本中迭代单选按钮值

时间:2014-12-04 20:15:52

标签: javascript forms for-loop google-apps-script

为雇主制定一个相当直接的项目。我需要一份调查表,提交时会将答案转储到电子表格中。我在独立应用上使用Google Apps脚本。项目管理层决定不使用Google表单。

我遇到的问题是检索单选按钮值。有很多单选按钮问题,我需要能够迭代它们来获取它们的值。

用户界面是通过GAS的UiApp服务完成的:

function doGet(e){
  var app = UiApp.createApplication();

  // set up the form
  var form = app.createFormPanel();
  var flow = app.createFlowPanel();
  form.add(flow);
  app.add(form);

  // create the radio button groups (they are all Likert scales). 
  // I've written a function that creates a single group (see below)
  for (var i=0; i<24; i++){
    likertScale(i, flow);
  };

  flow.add(app.createSubmitButton('Submit')

  return app;
}

我的likertScale()函数用于创建单选按钮组:

function likertScale(name, flow) {
  // the 'name' argument allows me to pass in the var i from the 
  // for loop above to give each radio button group a unique name
  // the 'flow' argument allows me to pass in the var flow that  
  // I created when setting up the form

  var app = UiApp.getActiveApplication();
  // create the N/A option, assign the group's name, give the button a label 
  // and a value
  flow.add(app.createRadioButton('item'+name, 'N/A').setFormValue('NA'));
  for (var j=1; j<6; j++) {
    // create the 5-point Likert scale; assign the group's name to each button,
    // use j to give each a label and a value
    flow.add(app.createRadioButton('item'+name,j).setFormValue(j);
  }

  return app;
}

为了测试检索值的前提,我正在添加其文本包含应用程序值的标签。功能的相关部分:

function doPost(e) {
  var app = UiApp.getActiveApplication();
  for (var i=0; i<24; i++){
    var radio = 'item'+i; 
      // I've previously set the name of each radio button group 
      // as 'item#', where # is a number 0-23. 
    app.add(app.createLabel().setText('You selected ' + e.parameter.radio));
      // The idea is that each iteration recreates the name of a radio
      // button, then uses that name to inform e.parameter.radio 
  };

  return app;
}

对我来说真正令人困惑的是,当上面的代码吐出'你选择未定义'24次时,下面的代码完全有效:

function doPost(e) {
  var app = UiApp.getActiveApplication();
  app.add(app.createLabel().setText('You selected ' + e.parameter.item0

  return app;
}

似乎只要我不尝试任何循环并且我手动编码整个事情,一切都很好。

对此有何见解?

1 个答案:

答案 0 :(得分:2)

你不能引用变量&#34; radio&#34;这样,它将被解释为一个名为&#34; radio&#34;尝试:

app.add(app.createLabel().setText('You selected ' + e.parameter[radio]));

在此处查看有关访问对象属性的方法的详细信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties