Written by: Geoffrey Callaghan
static website forms
Static Website Forms
Using Fabform for static website forms involves setting up HTML forms and using Fabform directives to enhance their functionality. Fabform helps with form validation, data binding, and submission handling, making it easier to work with forms in static websites. Here’s a step-by-step guide:
If you haven’t already, install Fabform via npm:
npm install fabform
You can include Fabform in your project either by using a module bundler like Webpack or by including it via a <script>
tag in your HTML file.
<script src="/path/to/fabform.js"></script>
Create an HTML form in your static website’s HTML file. You can use regular HTML form elements and enhance them with Fabform directives.
<form id="contactForm" fab-form name="contactForm" action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" fab-model="formData.name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" fab-model="formData.email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" fab-model="formData.message" required></textarea>
<button type="submit">Submit</button>
</form>
Use Fabform directives to enhance your form elements. For example, fab-form
initializes a Fabform instance, and fab-model
binds form input to a variable in your script.
Handle form submission either through JavaScript or a backend service. Fabform doesn’t handle form submission directly but helps with form validation and data binding.
Once the form is submitted, process the form data according to your needs. Since this is a static website, you might not have a backend, so you can use services like Formspree or Netlify Forms to handle form submissions.
const formData = {};
document.getElementById('contactForm').addEventListener('submit', async function(event) {
event.preventDefault();
// Do any client-side validation here if needed
// Submit the form data to a backend or service
try {
const response = await fetch('/submit', {
method: 'POST',
body: JSON.stringify(formData),
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
// Handle success
console.log('Form submitted successfully');
} else {
// Handle error
console.error('Form submission failed');
}
} catch (error) {
console.error('Error submitting form:', error);
}
});
Adjust the form submission handling according to your specific requirements and the backend or service you’re using for form submissions.