Home > Back-end >  How to enter validation for a choice of a question in Google forms using script editor?
How to enter validation for a choice of a question in Google forms using script editor?

Time:12-19

I want that when someone tries to fill the checkbox, the checkbox automatically unchecks itself according to the time of the day.

Here is my code: `

function myFunction() {
  var myForm = FormApp.getActiveForm();
  var title = myForm.getId();
  var choicesArray = [];
  var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is 
  var choices = item.getChoices();
  var d = new Date();
  choices.forEach(function(a) {
      if (a.checked == true && a.getValue() == "First")
          if (d.getHours() >= 17)
          a.checked = false;
      if (a.checked == true && a.getValue() == "Second")
          if (d.getHours() < 17)
          a.checked = false;
  });
}

` After creating trigger nothing happens and i am able to select both the checkboxes which shouldn't happen. Nor the trigger triggers.

if that is not possible then how to delete the second choice and only show the other one?

CodePudding user response:

The issue is that you have put semicolons right after if. This terminates the if.

Remove the semicolons & put the statements right after if instead of the next line.

function myFunction() {
  var myForm = FormApp.getActiveForm();
  var title = myForm.getId();
  var choicesArray = [];
  var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is 
  var choices = item.getChoices();
  var d = new Date();
  choices.forEach(function(a) {
      if (a.checked == true && a.getValue() == "First")
          if (d.getHours() >= 17); // <--- remove ;
          a.checked = false;
      if (a.checked == true && a.getValue() == "Second")
          if (d.getHours() < 17); // <--- remove ;
          a.checked = false;
  });
}

CodePudding user response:

Modification points:

  • Class Choice object has no property of checked. I thought that this might be the reason for your current issue. And, in the current stage, the checkbox cannot be set as the disable button. So, as a current workaround, how about if that is not possible then how to delete the second choice and only show the other one??

When these points are reflected in your script, how about the following modification?

Modified script:

function myFunction() {
  var myForm = FormApp.getActiveForm();
  var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is 
  var d = new Date();
  item.setChoices([item.createChoice(d.getHours() >= 17 ? "Second" : "First")]);
}
  • From your showing script, I used d.getHours() >= 17 ? "Second" : "First". If you wanted the reverse from this, please modify it to d.getHours() >= 17 ? "First" : "Second".

References:

  • Related