Search code examples
javascriptif-statementgoogle-apps-scriptmessagebox

If statement and variable set from browser message boxes


I have a simple script to send emails. The script prompts the user to enter their name, then each email is displayed in a message box and the user is prompted to confirm whether or not the email should be sent. If the user clicks "no", the email should not be sent.

Currently, the if-statements are not working properly, the email sends regardless of msgbox response.

I think it may be the value set by the message box for the variable called "confirm". It appears the confirm variable is somehow always set to "yes" even if you click no, not sure why.

EDIT: updated to working version.

function sendEmails1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setActiveSheet(ss.getSheetByName("Send-Emails 1"));
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:D10");
var data = dataRange.getValues();

var sender = Browser.inputBox('Sender Name', 'Please enter your first and 
  last name', Browser.Buttons.OK_CANCEL);

if(sender !='cancel'){
   for (i in data) {
    var rowData = data[i];
    var emailAddress = rowData[1];
    var recipient = rowData[2];
    var text1 = 'text';
    var text2 = 'text';
    var text3 = 'text';
    var text4 = 'text';
    var text5 = 'text';
    var signoff = 'Kind Regards,';
    var sendername = sender ;
    var org = 'text'; ; 
    var message = recipient + ',\n\n' + text1 + ' ' + text2 + ' ' + text3 + '\n\n' + text4 + '\n\n' + text5 + '\n\n' + signoff + '\n\n' + sendername + '\n\n' + org;
    var subject = 'text';

    //prompt the user with the composed email for review
    var confirm = Browser.msgBox('Send the following email?', 'To: ' + 
        emailAddress + '\\n\\n' + recipient + ',\\n\\n' + message, 
    Browser.Buttons.YES_NO);
    if(confirm==='yes'){
        MailApp.sendEmail(emailAddress, subject, message);
   }
  }
 }
}

Solution

  • Your if statement should use comparison == or ===.

    It should be

    if (confirm === 'yes')