Javascript - using form field values to determine which email address to use

417 Views Asked by At

Javascript newbie here, so apologies if this is incredibly basic and not the prettiest coding.

I'm creating a form that I want to have sent to a different email address depending on which team someone selects (e.g. if you select Sales it will generate an email to Team X, Refunds will email Team Y etc).

So far I've got to the stage where I can click a button to generate an email and attach the form as a PDF, but I don't know how to make it variable depending on the field value.

Current code:

var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;
//I've used a fake email address for the next line variable, but this is the one I want to change depending on the "WhichTeam" field value
var mailtoUrl = "mailto:[email protected]?subject=Callback Referral for " + customSubject;
this.submitForm({
 cURL: mailtoUrl,cSubmitAs: "PDF"});

Hope this makes sense. Grateful for any help/advice?

Thanks

1

There are 1 best solutions below

1
On

You can try using an object to contain the emails with the teams as they values. And to also use a template string to insert the value into the mailtoUrl.

var emails = {
   refunds: 'refundsTeamEmail',
   sales: 'salesTeamEmail',
}

var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;

// ex. customSubject value is 'refunds'
// emails[customSubject] would be the same as doing emails.refunds
// which return the value of 'refundsTeamEmail'
var mailtoUrl = `mailto:${emails[customSubject]}?subject=Callback Referral for ` + customSubject;
this.submitForm({
 cURL: mailtoUrl,cSubmitAs: "PDF"});

I think this is the simplest way to do it as the value will change each time you run the function to send the email without having to create or call other functions.

Having just said the last thing, you could also use a switch case in another function to return the value. If you want to. Something like:

function fetchEmail(email) {
   switch(email) {
      case 'refunds':
       return 'refundsTeamEmail'
      case 'sales':
       return 'salesTeamEmail'
      default:
       return ''
   }
}

var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;

// ex. customSubject value is 'refunds'
// emails[customSubject] would be the same as doing emails.refunds
// which return the value of 'refundsTeamEmail'
var mailtoUrl = `mailto:${fetchEmail(customSubject)}?subject=Callback Referral for ` + customSubject;
this.submitForm({
 cURL: mailtoUrl,cSubmitAs: "PDF"});