Search code examples
google-apps-scriptgoogle-forms

Adding choices to check box in google form


I am trying to add new options in a checkbox on Google forms. I am trying to have as many checkboxes as I do files to select from.

function listFilesInFolder() {  
  var folderName = "Box A";
  var folder = DriveApp.getFolderById('some id');
  var contents = folder.getFiles();

  var list = []; 
  list.push(['Name','ID','Size']);

  var files = folder.getFiles(); 
  while (files.hasNext()) {
    file = files.next();
    //spread sheet info if needed
    var row = []
    row.push(file.getName(), file.getId(), file.getSize())
    list.push(row);

    var name = file.getName();
    AddToDropDown(name);
    console.log(name)
  }
}

function AddToDropDown(name) {
  var form = FormApp.openById('some id');
  var items = form.getItems();
  var ImageSelection = items[7].asCheckboxItem();
  ImageSelection.setChoices([
    ImageSelection.createChoice(ImageSelection.getChoices().toString()),
    ImageSelection.createChoice(name),
  ])    
}

Ive tried it this way and as well as

function AddToDropDown(name) {
  var form = FormApp.openById('some id');
  var items = form.getItems();
  var ImageSelection = items[7].asCheckboxItem();
  ImageSelection.createChoice(name);   
}

Neither seem to work. Any Thoughts?


Solution

    • You want to add the filenames retrieved from a folder as checkboxes.
    • You want to give each filename to each checkbox.

    If my understanding is correct, how about this modification? In this modification, your script was modified.

    Flow of this modified script:

    1. Retrieve filenames and put them to an array.
    2. Create "Choice" objects using createChoice() with the retrieved filenames.
    3. Set the "Choice" objects using setChoices().

    Modified script:

    function addfileselect() {
      var folder = DriveApp.getFolderById('1--5CnFK5DtptuO1bUu6MsA9oTknr-Fw2');
      var files = folder.getFiles();
      var names = [];
      while (files.hasNext()){
        var file = files.next();
        names.push(file.getName());
      }
      var form = FormApp.openById('1gcktQP5bKxCtAvtlgz4d9x7zI6M4koRmZkkjgefswIg');
      var items = form.getItems();
      var ImageSelection = items[7].asCheckboxItem();
      var choices = ImageSelection.getChoices();
      for (var i = 0; i < names.length; i++) {
        var choice = ImageSelection.createChoice(names[i]);
        choices.push(choice);
      }
      ImageSelection.setChoices(choices);
    }
    

    Note:

    • In this modification, if there are the existing checkboxes, the checkboxes of filenames are added. If you want to added only the checkboxes of the retrieved filenames, please replace var choices = ImageSelection.getChoices(); to var choices = [];.
    • It might occur an error when the number of added checkboxes is large.

    References:

    If I misunderstood your question and this was not the result you want, I apologize.