By gobrain
HTML forms are an essential component in any web pages, allowing users to input data and interact with websites. They enable you to obtain information from users and send it to a server for processing, managing and storing.
In this article, we will cover the basics of HTML forms, including how to create them and handle user input.
To create a form, HTML provides a wrapper <form> tag, within which other form elements are placed. We will be discussing later these elements. Now, Let's see the form tag itself and its main attributes.
<form action="/submit-form" method="POST">
<!-- form elements go here -->
</form>
As you can see, there are two exclusive attributes in a html form:
Simply put, when the form above is submitted, it sends a post request to the /submit-form endpoint on the server, so that the server can process the form data that is obtained from the user via form elements, which we will discover in the next step.
HTML provides several types of form elements, each with its own set of attributes and behaviors. Here are some of the most common form elements:
As its name suggests, input fields are used to gather user input from users. The type attribute determines the behavior and functionality of the input tag. Let's discover each in a code snippet.
<input type="text" name="username" />
<input type="password" name="password" />
<input type="email" name="email" />
<input type="number" name="age" />
<input type="checkbox" name="agree" />
<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />
You can see the appearance of each in the following image:
Select fields allow users to select an option from a dropdown list. The option tags specify the available options.
<select name="country">
<option value="usa">United States</option>
<option value="canada">Canada</option>
<option value="uk">United Kingdom</option>
</select>
Here is the select element grouping different countries:
Textarea fields allow users to enter multiple lines of text.
<textarea name="comments"></textarea>
Submit buttons are used to submit the form data to the server.
<button type="submit">Submit</button>
Once a user submits a form, the data is sent to the server for processing. The server then typically responds with a new page or a message indicating whether the form submission was successful or not.
To handle form data, you can use a server-side programming language such as PHP, Python, or Ruby. Alternatively, you can use client-side JavaScript to perform form validation and submission without requiring a server-side component.
There are several ways to handle form data with JavaScript, depending on the task at hand. Let's explore some of the most common methods.
Form validation is the process of checking whether the user input is valid before sending it to the server. This can help to reduce server load and improve the user experience by catching errors before the user submits the form.
JavaScript provides several methods for form validation, such as the checkValidity() method, which checks whether the form is valid, and the setCustomValidity() method, which sets a custom error message for the form element.
Here is an example of how to use the checkValidity() method:
<form id="myForm">
<input type="text" required>
<input type="submit" value="Submit" onclick="validateForm()">
</form>
<script>
function validateForm() {
const form = document.getElementById("myForm");
if (form.checkValidity() === false) {
alert("Please fill out all required fields");
return false;
}
}
</script>
In this example, the checkValidity() method is called on the form element when the submit button is clicked. If any required fields are empty, an alert is shown to the user, and the form is not submitted.
Once the form data has been validated, it's time to handle the data submission. In modern web development, the most common way to handle form submission is by using AJAX (Asynchronous JavaScript and XML) to submit the form data to the server without refreshing the page.
To do this, we can use the fetch API or any other library like axios or jQuery. Let's take a look at an example of how to use the fetch API to submit form data:
const form = document.querySelector('#myForm');
const formData = new FormData(form);
fetch('/submit', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Form submitted successfully', data);
})
.catch(error => {
console.error('There was a problem submitting the form', error);
});
In this example, we first select the form element using the querySelector method. We then create a new FormData object with the form element as its argument. This allows us to easily retrieve all the form data as key-value pairs.
We then use the fetch API to send a POST request to the server with the form data as the request body. The server can then process the data and return a response.
The fetch method returns a promise which resolves with the server's response. We can then check if the response was successful and parse any JSON data returned by the server.
Handling form data with JavaScript can be a complex task, especially when it comes to validation and security. It's important to ensure that all user input is properly validated on both the client and server side to prevent malicious attacks.
HTML forms are an essential component of web development, allowing users to input data and interact with websites. By understanding how to create and handle form data, you can create powerful and engaging web applications that provide a great user experience.
Thank you for reading.