본문으로 건너뛰기

Implementing Contact Form Functionality

Implementing Contact Form Functionality

Contact forms on websites often provide the functionality to send information received from users to an email. This section explains how to implement this functionality using JavaScript to send information to an email client.


sendEmail Function Explanation

This function handles the action of sending contact information to an email using the information entered by the user.

Variable Setup

  • button: Selects the element with the ID 'send-button' from the document. This refers to the button that the user clicks to send the information.
const button = document.getElementById('send-button');

Adding Event Listener

  • Add a 'click' event listener to button, defining the callback function to be executed when the click event occurs.

  • In the callback function, call e.preventDefault() to prevent the default submission behavior of the form.

  • Then, retrieve each piece of information entered in the contact form.

button.addEventListener('click', function (e) {
e.preventDefault();
const name = document.getElementById('input-name').value;
const phone = document.getElementById('input-phone').value;
const email = document.getElementById('input-email').value;
const message = document.getElementById('input-message').value;
// ...
});

Sending Email

  • Use the collected information to define the email address, subject, and content.

  • Use window.location.href to open the mail client and compose the email. The subject and body of the email are written using the variables defined earlier.

const subject = 'Contact Information';
const body =
'Name: ' +
name +
'%0D%0A' +
'Phone: ' +
phone +
'%0D%0A' +
'Email: ' +
email +
'%0D%0A' +
'Message: ' +
message;

window.location.href =
'mailto:recipient@example.com?subject=' + subject + '&body=' + body;

Using the above code, when the user clicks the 'send-button' in the contact form, the email client will open, and an email containing the entered information can be composed.

Here, 'recipient@example.com' should be changed to the email address of the recipient.