Skip to main content
Practice

Implementing a Contact Form

A website contact form often provides functionality to send the user's input information via email. This section explains how to implement this functionality in JavaScript by using an email client to send the captured information.


Explanation of the sendEmail Function

This function handles sending contact information via email based on user input from the contact form.

Variable Setup

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

Adding an Event Listener

  • Adds a 'click' event listener to the button, defining a callback function that will execute when the click event occurs.

  • Calls e.preventDefault() within the callback function to prevent the default form submission behavior.

  • Then, it retrieves each piece of information entered into 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 the Email

  • Defines the email address, subject, and body content using the captured information.

  • Uses window.location.href to open the mail client and compose an email with the defined subject and body content, using the previously defined variables.

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 code above, when the user clicks the 'send-button' on the contact form, the mail client will open and compose an email containing the information entered in the form.

Here, 'recipient@example.com' should be replaced with the recipient's email address.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.