DEV Community

Cover image for Creating an Interactive Contact Form with HTML, CSS, and JavaScript
GetSmartWebsite
GetSmartWebsite

Posted on

Creating an Interactive Contact Form with HTML, CSS, and JavaScript

A contact form is more than just a means for your website visitors to get in touch with you. It's also an opportunity to gather valuable information about them and understand their needs better. In this guide, we'll walk you through the process of creating a modern, interactive contact form using HTML, CSS, and JavaScript.

Designing the Form with HTML and CSS

First, let's set up the HTML structure of our form. The following is a basic layout:

<form id="contactForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea>
  <button type="submit">Send</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Next, let's add some CSS to make our form visually appealing:

form {
  display: flex;
  flex-direction: column;
}
input, textarea {
  margin-bottom: 15px;
  padding: 10px;
}
button {
  padding: 10px 20px;
}
Enter fullscreen mode Exit fullscreen mode

Making the Form Interactive with JavaScript

Now, let's enhance our form with JavaScript to make it more interactive. We'll add form validation to ensure the user provides valid input:

document.getElementById('contactForm').addEventListener('submit', function(event) {
  var name = document.getElementById('name').value;
  var email = document.getElementById('email').value;
  var message = document.getElementById('message').value;

  if (name == "" || email == "" || message == "") {
    alert("All fields must be filled out");
    event.preventDefault();
  } else if (!email.includes("@")) {
    alert("Please enter a valid email address");
    event.preventDefault();
  }
});
Enter fullscreen mode Exit fullscreen mode

This is a simplified form of validation and just a starting point. If you're looking to create more complex forms, you might need more sophisticated validation. Professional web design companies, like GetSmartWebsite, often use libraries like jQuery Validate to ensure form data integrity while providing a user-friendly experience.

Connecting the Form to a Server with Fetch API

Our form is looking good and functioning well, but we want the data to be sent to a server when the form is submitted. For this, we'll use the Fetch API:

document.getElementById('contactForm').addEventListener('submit', function(event) {
  event.preventDefault();

  var name = document.getElementById('name').value;
  var email = document.getElementById('email').value;
  var message = document.getElementById('message').value;

  fetch('https://your-server.com/contact', {
    method: 'POST',
    body: JSON.stringify({
      name: name,
      email: email,
      message: message
    }),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  }).then(data => {
    console.log('Success:', data);
  }).catch((error) => {
    console.error('Error:', error);
  });
});
Enter fullscreen mode Exit fullscreen mode

This script will send the form data to your server when the form is submitted. Make sure to replace https://your-server.com/contact with the actual URL of your server's endpoint.

Conclusion

And there you have it! You've just created a modern, interactive contact form with HTML, CSS, and JavaScript. Remember, this is just a starting point.

There are many other features you can add to your forms, like auto-complete, multi-step processes, and more. But the principles remain the same: gather user input in a user-friendly way, validate that input, and then do something with the data. Now go ahead and start experimenting with your own form designs!

Top comments (4)

Collapse
 
jaisysymuri profile image
JaisySymuri

Maybe out of topic. I want to create a tutorial myself but the code block I made isn't colorful like the tutorial you made (and other many tutorials here). How to make it?

document.getElementById('contactForm').addEventListener('submit', function(event) {
  event.preventDefault();

  var name = document.getElementById('name').value;
  var email = document.getElementById('email').value;
  var message = document.getElementById('message').value;

  fetch('https://your-server.com/contact', {
    method: 'POST',
    body: JSON.stringify({
      name: name,
      email: email,
      message: message
    }),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  }).then(data => {
    console.log('Success:', data);
  }).catch((error) => {
    console.error('Error:', error);
  });
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
diomed profile image
May Kittens Devour Your Soul • Edited

after you open code block tags add word js

Collapse
 
jaisysymuri profile image
JaisySymuri

It works! Thank you!

Collapse
 
nyangweso profile image
Rodgers Nyangweso

thanks for sharing