Written by: Geoffrey Callaghan
Convert A Contact Form Into JSON format
Convert A Contact Form Into JSON format
Converting a contact form submission into JSON format can be useful for processing and handling the form data in a structured way. This tutorial will guide you through the process of converting a basic HTML contact form into JSON using JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form to JSON</title>
</head>
<body>
<h2>Contact Form</h2>
<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" rows="4" cols="50" required></textarea>
<input type="submit" value="Submit">
</form>
<script src="script.js"></script>
</body>
</html>
document.getElementById('contactForm').addEventListener('submit', function(event) {
// Prevent the default form submission
event.preventDefault();
// Create an object to store form data
var formData = {};
// Iterate through each form element and add it to the formData object
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
// Check if the element has a name and is not a submit button
if (element.name && element.type !== 'submit') {
formData[element.name] = element.value;
}
}
// Convert the formData object to JSON
var jsonData = JSON.stringify(formData, null, 2);
// Display the JSON data (you might want to send it to the server instead)
console.log(jsonData);
});
addEventListener
.event.preventDefault()
to handle the submission via JavaScript.formData
to store the form data.formData
object, excluding the submit button.JSON.stringify
method is used to convert the formData
object into a JSON-formatted string.This simple tutorial demonstrates how to convert a basic contact form submission into JSON using JavaScript. Depending on your application’s needs, you may want to enhance this process by adding form validation, error handling, and integrating it with a backend server for data processing.