7
votes

I have a good form, where a user submits data. For learning, I have only one form field, which is a radio button with 2 options. The resulting spreadsheet has only 2 cols, "Timestamp" and "names."

The goal of my script is to evaluate the event-driven data from the form submission, and then change the value in a variable so emails can be sent to different users. The case never evaluates, and the result is always default. Here is my script which of which is from other sources: Digital Inspiration.

function Initialize() { var triggers = ScriptApp.getScriptTriggers(); for(var i in triggers) { ScriptApp.deleteTrigger(triggers[i]); } ScriptApp.newTrigger("SendGoogleForm") .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit() .create(); } function SendGoogleForm(e) {
try {

var subject = "Form Test";  

var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];    
var message = "";    

// Credit to Henrique Abreu for fixing the sort order

for(var i in headers) {
  message += headers[i] + ' :: '+ e.namedValues[headers[i]].toString() + "\n\n"; 
}

message += headers[1] + "\n";
message += e.namedValues[headers[1]]; \\ I left this in to check datavalues in the email
message += e.namedValues[headers[1]]; \\ I left this in to check datavalues in the email
message += e.namedValues[headers[1]] + "\n";

var email = e.namedValues[headers[1]].toString; \\ I would ASSUME that this would store \\the spreadhseet data to the variable email,

but it doesn't seem to do that.

message += "Sheet URL :: " + SpreadsheetApp.getActiveSpreadsheet().getUrl() + "\n";

     switch (email)
    {
        case "basdf":
            email = "[email protected]";
            break;
        case "dfdsa":
            email = "[email protected]";
            break;
        default:
            email = "[email protected]";
            break;
    }




MailApp.sendEmail({
  to: email,
  subject: subject,
  body: message,
  })
   } catch (e) {
Logger.log(e.toString());   }
 }
1

1 Answers

12
votes

Try this snippet. It checks the header column name with the form submitted value and then assigns the corresponding value to the email variable.

var email = "";

for(var i in headers) {
  if (headers[i] == "email") {
     email = e.namedValues[headers[i]].toString();
  }
  message += headers[i] + ' :: '+ e.namedValues[headers[i]].toString() + "\n\n"; 
}

switch (email)  {
        case "basdf":
            email = "[email protected]";
            break;
        case "dfdsa":
            email = "[email protected]";
            break;
        default:
            email = "[email protected]";
            break;
    }