0

I am creating an email app that sends messages to other people. Currently, I have it working except for the recipients column. Right now, I hard-coded an email into the recipients column to get it working. The reason is, is the recipients field is supposed to be an array.

What's the best way of passing a value from a user form (multiple addresses separated by commas) into JSON format?

Below is how I have it now.

Thanks!

const element = document.getElementById('sendEmail');
  element.addEventListener('click', function() {
    fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: '[email protected]',
      subject: document.querySelector('#compose-subject').value,
      body: document.querySelector('#compose-body').value
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
  });
  });
}
3
  • Can't you make it an array directly? {recipients: ['[email protected]','[email protected]'], subject: document.querySelector('#compose-subject').value, body: document.querySelector('#compose-body').value } Commented Oct 27, 2020 at 20:24
  • is value like a string separated by comma and you need to convert this value to array? Commented Oct 27, 2020 at 20:27
  • 1
    Questions asking about "the best way" are not a good fit for Stack Overflow. The best way is often different based on your use case. It's unclear what you're having difficulty with. You have not shown an attempt to pass the email list to the backend. There are different ways to do it. It could be a comma/space separated string or it could be an array and the first two comments mentioned Commented Oct 27, 2020 at 20:29

1 Answer 1

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

    const emailsFromForm = [ // NEW
      document.querySelector('#email1').value, // NEW
      document.querySelector('#email2').value // NEW
    ] // NEW

    fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: emailsFromForm, // EDITED
      subject: document.querySelector('#compose-subject').value,
      body: document.querySelector('#compose-body').value
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
  });
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.