Converting an array value into JSON structure

I'm currently working on an email application that allows users to send messages. Everything is functioning well except for the recipients column. I temporarily hardcoded an email address to test the functionality, but in reality, the recipients field should be an array.

What would be the most efficient way to convert multiple addresses entered by a user into JSON format within a form?

The snippet below demonstrates my current approach.

Thank you!

const element = document.getElementById('sendEmail');
  element.addEventListener('click', function() {
    fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7c7e6d7b2a2e6c77706d6b5f78727e7673317c7072">[email protected]</a>',
      subject: document.querySelector('#compose-subject').value,
      body: document.querySelector('#compose-body').value
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
  });
  });
}

Answer №1

const target = document.getElementById('sendEmail');
  target.addEventListener('click', function() {

    const emailsList = [ // UPDATED
      document.querySelector('#email1').value, // ADDED
      document.querySelector('#email2').value // ADDED
    ] // MODIFIED

    fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: emailsList, // CHANGED
      subject: document.querySelector('#compose-subject').value,
      body: document.querySelector('#compose-body').value
    })
  })
  .then(response => response.json())
  .then(result => {
      // Display result
      console.log(result);
  });
  });
}

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

Activate Input by Clicking on Label in Internet Explorer version 8

I am trying to implement a widget in JQuery colorbox that allows users to load files. My approach involves using an input tag with type='file' and styling it with visibility:hidden. Additionally, I have created two labels that are styled like but ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Storing JSON data in an SQLite database involves creating a table with a

I'm having trouble figuring out how to save data in 'JSON' format into my sqlite database for a Rails application. I've looked into various methods, but so far haven't found any promising solutions. Can anyone provide guidance on h ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

Creating Transparent Rounded Backgrounds in Google Chrome Packaged Apps: Achieving the same look as Google Hangout app

Looking at the screenshot below, it is evident that the Hangout app has a fully transparent design with background shadow effect applied to it. I have tried various methods in vain, such as applying CSS styling to the "html" and "body" tags of the page, a ...

Encountering challenges with managing global variables in my Node.js application

I am facing a problem with global variables in my NodeJs application. The project involves webservices created using the express module. When a client accesses the service, a json object is sent in the request body. I extract all properties from the reques ...

Using jQuery setTimeout within a forEach loop

Currently, I am fetching an array of messages using 'getJSON method. My intention is to display each message for 3 seconds before moving on to the next one. The process involves loading an HTML file and applying a CSS class to each message. However, m ...

Having trouble retrieving a value within the jQuery.ajax success function

I need to implement jQuery Validator in order to validate if a user's desired username is available during the sign-up process. The PHP script untaken.php is responsible for checking this, returning either ok if the username is free or taken if it is ...

Converting JSON into an interface in TypeScript and verifying its validity

How can I convert a JSON string to a nested interface type and validate it? Although my model is more complex, here is an example: export interface User = { name: Field; surname: Field; }; export interface Field = { icon: string; text: string; vis ...

Emulating a mouse click in jQuery/JavaScript on a webpage link

I am seeking a way to programmatically trigger a click on any link within a webpage using JavaScript. The challenge lies in ensuring that if the link has an 'onclick' event bound to it by another unknown JavaScript function, that event is trigger ...

Using JQuery, remove any duplicate items from one list box and populate another list box

I have two list boxes set up: the leftBox contains all available options, while the rightBox displays the selected options. I am already familiar with how to add and remove items from each list box using jquery. However, my current goal is to automatically ...

What is the best way to upload multiple files using ASP.Net and Jquery?

On my aspx page, I have included the following JavaScripts... <script src="jquery-1.3.2.js" type="text/javascript"></script> <script src="jquery.MultiFile.js" type="text/javascript"></script> In addition, I have inserted the follo ...

"Encountering issues with createReadStream function when handling large files, performance is significantly

Currently, I am utilizing the DropBox API for file uploads. The process involves several steps: Begin by uploading the file from a form to a local directory on the server. Read the file from the local directory using fs.createReadStream. Transfer the fil ...

How can I delete a pathway in paper.js?

Is it possible to create a new path using the canvas globalCompositeOperation set to 'destination-out'? If so, how would I go about doing this? I have observed that Item has a blendMode property which can be found at . However, experimenting wit ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Executing Jquery AJAX will continue to submit the form regardless of the confirmation status returned by the confirm()

<div class="report" data-id="55"></div> <script> $('.report').click(function() { var id = $(this).data("id"); confirm("do you really want to report this post?"); $.ajax({ url: 'forumreport.php', ...

Executing $(this).parent().remove() triggers a full page reload

A unique feature of my webpage is that with just a simple click of a button, users have the ability to dynamically add an endless number of forms. Each form contains fields for user input and also includes a convenient delete button. var form = " Name ...

Utilize JSON files to enable parameterization and run multiple test iterations

Working with a file named test_data.json, the goal is to generate test iterations in Python. The file contains values that need to be passed to specific methods, with the assertion part being handled separately and not requiring the JSON file data. To ach ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...