Tips for styling text in a mailto function

I am working with two arrays and an object in my project. The first array contains product codes, while the second array contains the quantities of each product. The quantities array corresponds to the product codes array, meaning the first quantity in the quantities array is for the first product code in the product codes array. Additionally, I have an object that holds customer data structured like this:

customer={
name:' firstname lastname',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceabb6afa3bea2ab8eaaa1a3afa7a0e0ada1a3">[email protected]</a>',
company: "company name",
phone_number: 'phone number',
}

The product codes array and quantities array are as follows:

product_codes=[code_1; code_2; code_3];
quantities=[23, 56, 45];

All this information is intended to be sent to [email protected].

I know the basics of using the mailto function, but I am looking for a way to format the email body as specified below:

...................................

Name: customer.name

email: customer.email

company name: customer.company

phone number: customer.phone_number

product code 1: corresponding quantity

product code 2: corresponding quantity

product code 3: corresponding quantity

...............................................

I also need to dynamically add any other product codes and quantities, as the number is variable in each case. Is this feasible? If yes, how can it be achieved? Kindly provide a detailed explanation for practical implementation. Thank you!

If my query is unclear, please let me know so I can clarify it further.

Answer №1

function sendEmail() {

  var customer, body, quantities, product_codes;    

  customer = {
    name: 'John Doe',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c6dbc2ced3cfc6e3c6dbc2ced3cfc68dc0ccce">[email protected]</a>',
    company: 'XYZ Company',
    phone_number: '123-456-7890',
  }

  body =  'Name: '+ customer.name;
  body += '\nEmail: '+ customer.email;
  body += '\nCompany: '+ customer.company;
  body += '\nPhone Number: '+ customer.phone_number;

  product_codes = ['item_1', 'item_2', 'item_3'];
  quantities = [10, 20, 30];

  for(var i = 0; i < product_codes.length; i += 1) {
    body += '\nItem Code '+ product_codes[i] +': '+ quantities[i];
  }

  subject = 'Your Message Subject';

  window.location = 'mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2918781869d9f9f9780818782829d8086b2978a939f829e97dc919d9f">[email protected]</a>?body='+ encodeURIComponent(body) +'&subject='+ encodeURIComponent(subject);

};

// Run this function when the user clicks the #send-email button
var button = document.getElementById('send-email');
button.addEventListener('click', sendEmail);

https://i.sstatic.net/EaRs6.png

Answer №2

To achieve this functionality, I suggest creating a function to build the string:

Below is the HTML code:

<a href="#" id="thelink">Click to Email</a>

And here is the JavaScript code:

// First, define the necessary data
var customer={
  name:'John Doe',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedbc6dfd3ced2dbfedad1d3dfd7d090ddd1d3">[email protected]</a>',
  company: "Example Company",
  phone_number: '555-555-5555',
}
var product_codes=['alpha', 'beta', 'gamma'];
var quantities=[23, 56, 45];

// Assign a click action to the link
var yourLink = document.getElementById("thelink");
yourLink.onclick = function() {
   var elf = "%0A"; //Encoded Line Feed
   mailtoBody = "Name: " + customer.name + elf
              + "Email: " + customer.email + elf
              + "Company Name: " + customer.company + elf
              + "Phone Number: " + customer.phone_number + elf;
   for (var i=0; i < product_codes.length; i++) {
        mailtoBody += product_codes[i] + ": " + quantities[i] + elf;
   }
   location.href = "mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a33253f0a2f322b273a262f64292527">[email protected]</a>?body=" + mailtoBody;
}

You can test the functionality in this live example: http://jsbin.com/kigutuhiqa/edit?html,js,output

Answer №3

If you're looking to create the content of a message, one approach is to develop a function that assembles the message body using the three elements you specified: customer, codes, and quantity.

Here's an example:

function constructMessageBody(customer, productCodes, quantities){
    var messageBody = "";

    messageBody += "Name: " + customer.name + "\n";
    messageBody += "Email: " + customer.email + "\n";
    messageBody += "Company Name: " + customer.companyname + "\n";

    for(var i=0; i<productCodes.length; ++i)
        messageBody += "Product Code " + productCodes[i] + ": " + quantities[i] + "\n";

    return messageBody;
}

This code hasn't been validated, but I hope it gives you a clearer picture.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

Mastering the Art of Disabling buttons in Vue Based on Conditions

In my current project, I'm attempting to compare specific values of an initial object with an updated object in order to disable a button if they are the same. However, despite making changes, the button remains disabled: setDisabled() { return th ...

retrieving the value of an object key based on changing information

console.log(x, obj.fares) //return undefined output adultFare Object {adultFare: "9.00", childFare: null, seniorCitizenFare: null, disabledFare: null,} How do I retrieve the adultFare value from the object? Is looping through the keys necessary? I expec ...

What is the best method to reset numerous select boxes within a form using jQuery?

What is the best way to reset multiple select boxes within a dynamically generated form using jQuery? There are several select boxes that may have selected options The select boxes are not known in advance as they are generated dynamically Some option ta ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

Sorting a JSON Array by Key

I have a code snippet for extracting JSON data from the API: try { // establish connection with Zabbix-API $api = new ZabbixApi($api_url, $username, $password); $params = array( 'groupids' => '2&ap ...

Trouble with passing data from action to reducer in Redux with React Native

As a newcomer to Redux, I'm encountering an issue while trying to make an API call in the Action and pass the data to the reducer. Although I can see the response from the API call, there seems to be a problem with sharing the data correctly with the ...

CSS button pressed

I came across a helpful discussion on the topic of CSS for pressed buttons, which provided some answers that I found useful. The link to the discussion can be found here: Pressed <button> CSS. Currently, I have a button within a link and I would lik ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

Displaying multiple categories of articles on a single page with Node.js

Seeking a solution to limit the number of posts displayed for each category using a .limit() function, but uncertain on how to proceed. Currently utilizing Mongoose and Express in my code setup. The existing code snippet is outlined below: router.get(&a ...

Global variables in AngularJS that are asynchronous

My challenge lies in using AngularJS to create several global objects accessible by any controller within the application. One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the databa ...

Unable to display elements from an array in the dropdown menu generated by v-for

Having just started learning Vue.js, I am facing a challenge in rendering the following array: countries: ["US", "UK", "EU" ] I want to display this array in a select menu: <select> <option disabled value="">Your Country</option& ...

Differences between variable scope in Node.js and web browsers when running JavaScript code

When it comes to browser, different JavaScript files share one scope: a.js: var a=1; //by adding "var", we prevent it from becoming a global variable. b.js: console.log(a) //even though a=1, b.js can still access this variable! In Node.js: a.js .... b ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written: <!doctype html> <html lang="en"> <head> <title>Testing form input</title> <style type="text/css></style> <script type="text/javascript" src="validation.js"></script> &l ...

Exploring the wonders of Lightbox when dealing with content loaded via AJAX

Using Bootstrap 5 along with the Lightbox library from , I encountered an issue. The Lightbox feature functions properly on regular page loads, but fails to load on content loaded via AJAX. I attempted to resolve this by implementing the following code: ...

Experimenting with a Jest test on an express middleware

I'm currently faced with a challenge in testing my controller (express middleware) using Jest. To better illustrate the issue, I will share the code snippet below: import request from 'utils/request'; import logger from 'config/logger& ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

An issue occurred while attempting to release memory allocated for char

This block of code has been causing me a headache: I have spent countless hours trying to troubleshoot the issue, but all my efforts have been in vain #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string. ...