Building an HTML Form
Forms are containers for different types of input elements. Key tags include <form>
, <label>
, <input>
, <textarea>
, <select>
, and <button>
.
Crucial for Accessibility: Always use the <label>
element and connect it to its input using the for
attribute. This helps users of screen readers understand the form.
JavaScript Interaction
By default, submitting a form reloads the page. We can use JavaScript to intercept this event, grab the data, and do something with it (like display it or send it to a server) without a disruptive page refresh.
Live Form Output:
Submit the form to see the captured data here.
The JavaScript Code
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('interactive-form');
const outputDiv = document.getElementById('form-output');
form.addEventListener('submit', (event) => {
// 1. Prevent the default page reload
event.preventDefault();
// 2. Create a FormData object to easily access form data
const formData = new FormData(form);
// 3. Create an HTML string to display the result
let outputHTML = '<h3>Form Data Captured!</h3><ul>';
// 4. Loop through the form entries and add them to the list
for (const [key, value] of formData.entries()) {
outputHTML += `<li><strong>${key}:</strong> ${value || ' (empty)'}</li>`;
}
outputHTML += '</ul>';
// 5. Update the page with the new HTML
outputDiv.innerHTML = outputHTML;
});
});