Written by: Geoffrey Callaghan
How To Create A Contact Form In Alpine.js
How To Create A Contact Form In Alpine.js
How to create a contact form in Alpine.js with FabForm.io, you can follow these steps:
Sign Up on FabForm.io:
Create a Form:
Get the Form Endpoint:
Include Alpine.js:
Make sure to include Alpine.js in your HTML. You can include it from a CDN or install it via npm.
<!-- Include Alpine.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/alpinejs@2.8.2/dist/alpine.min.js" defer></script>
Or install it via npm:
npm install alpinejs
Then include it in your JavaScript file:
import 'alpinejs';
Create the Contact Form HTML:
Create an HTML file for your contact form, for example, contact-form.html
. In this file, use Alpine.js directives for data binding and form submission.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<!-- Include Alpine.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/alpinejs@2.8.2/dist/alpine.min.js" defer></script>
</head>
<body x-data="{ name: '', email: '', message: '' }">
<div>
<h1>Contact Us</h1>
<form x-on:submit.prevent="submitForm">
<label>
Name:
<input x-model="name" type="text">
</label>
<label>
Email:
<input x-model="email" type="email">
</label>
<label>
Message:
<textarea x-model="message"></textarea>
</label>
<button type="submit">Submit</button>
</form>
</div>
<script>
function submitForm() {
// FabForm.io endpoint
const endpoint = 'YOUR_FABFORM_ENDPOINT';
// Data to be submitted
const data = {
name: this.name,
email: this.email,
message: this.message,
};
// Submit the form using fetch
fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(() => {
console.log('Form submitted successfully');
// Optionally, reset the form fields
this.name = '';
this.email = '';
this.message = '';
})
.catch((error) => {
console.error('Error submitting form:', error);
});
}
document.querySelector('[x-data]').__x.$watch('name', value => {
console.log(value);
});
</script>
</body>
</html>
Replace ‘YOUR_FABFORM_ENDPOINT’:
'YOUR_FABFORM_ENDPOINT'
in the script with the actual endpoint you obtained from FabForm.io.Run Your Application:
By following these steps, you should be able to create a contact form in Alpine.js that submits data to FabForm.io. Customize the form and styling as needed for your application.