Jay Visariya
Jay Visariya

Reputation: 83

how to mail only the filled values and not the blank values in google form?

I have a made a google form which has many fields. I have put a trigger to send the form values to a particular(Also saves it in excel sheet in google drive). But it also mails me the blank values, which user hasn't selected. How should I sent only the filled values to mail by modifying the below code.

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 email ="[email protected]";

    var subject = "Form Submission";  

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

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

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

    MailApp.sendEmail(email, subject, message); 

  } catch (e) {
    Logger.log(e.toString());
  }

}

Please help me how to do it. Thank you :)

Upvotes: 1

Views: 289

Answers (2)

delliottg
delliottg

Reputation: 4140

Another way to do this is with a ternary statement:

message += e.namedValues[headers[i]] != "" ? e.namedValues[headers[i]].toString() + "\n\n" : "";

I use this in GAS/Javascript scripts to keep from sending extraneous data in the resultant emails.

Upvotes: 1

Jay Visariya
Jay Visariya

Reputation: 83

I found out the way to my question. It was just to add a simple if statement inside the for loop.

Solution:

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

Upvotes: 0

Related Questions