Skip to content

HTML and Vanilla JS

This guide will show you how to set up a contact form using HTML and Vanilla JS. The advantage of using JS to submit the form is that you can keep the user on the same page and show them a success message, instead of redirecting them to a new page. This way you can also create custom form validation and integrations with other services.

HTML

<form method="POST" id="form">
<input type="hidden" name="access_key" value="YOUR_ACCESS_KEY" />
<input type="hidden" name="subject" value="New form submission" />
<input type="checkbox" name="botcheck" id="" style="display: none;" />
<!-- Form data -->
<input type="text" name="name" required />
<input type="email" name="email" required />
<textarea name="message"></textarea>
<button type="submit">Submit</button>
<div id="result"></div>
</form>

JavaScript

const form = document.getElementById('form');
const result = document.getElementById('result');
async function handleSubmit(e) {
e.preventDefault();
result.innerHTML = 'Please wait...';
const formData = new FormData(form);
const json = JSON.stringify(Object.fromEntries(formData));
const res = await fetch('https://api.dev-forms.com/v1/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: json,
});
if (!res.ok) {
result.innerHTML = 'Something went wrong!';
}
const data = await res.json();
if (!data.success) {
console.log(data.body.message);
result.innerHTML = 'Something went wrong!';
return;
}
result.innerHTML = 'Thanks for contacting us!';
form.reset();
}
if (form && result) {
form.addEventListener('submit', handleSubmit);
}