-3

I want to create a text input form on a static page and convert that to an email body using the mailto option. For example, the following with take the input from the text box

<form action="/action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>

and in the email body will display as

Hello ABC,

The details are:

First Name: Mickey
Last Name: Mouse

Thanks,
XYZ
Shantanu
  • 839
  • 13
  • 27

1 Answers1

1

I've taken the time to round up a few answers for you. I hope that you take the time to read through each of the links provided.

First you want to get your form data as an object:

const formToJSON = elements => [].reduce.call(elements, (data, element) => {  
  data[element.name] = element.value;
  return data;
}, {});

I've used destructuring assignment to set defaults for some constants to use in the mailto:

const { 
  recipientName = "ABC", recipientAddress = "abc@123.yes",
  subject = "Some mailz for youz", senderName = "XYZ",
  firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))

We also need some linebreaks in our email body:

const lineBreak = "%0D%0A"

And finally template literals to construct our href for mailto:

const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`

Here's the snippet so you can see it all working together:

const formToJSON = elements => [].reduce.call(elements, (data, element) => {  
  data[element.name] = element.value;
  return data;
}, {});

const { 
  recipientName = "ABC", recipientAddress = "abc@123.yes",
  subject = "Some mailz for youz", senderName = "XYZ",
  firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))

const lineBreak = "%0D%0A"

const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`

const link = document.createElement("a")
link.textContent = "Send some mailz yaaaal"
link.href = mailTo
document.body.appendChild(link)
<form action="/action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>
BlueWater86
  • 1,773
  • 12
  • 22