In this lesson, we will explore HTML forms and learn how to work with form elements.
HTML forms are an essential part of building interactive websites. They allow users to input data and submit it to a server for further processing. Forms are commonly used for tasks such as user registration, contact forms, and online surveys.
To create a form in HTML, we use the form
element. Within the form, we can add form elements such as input fields, checkboxes, radio buttons, dropdowns, and buttons.
Let's take a look at an example of an HTML form:
1<!DOCTYPE html>
2<html>
3<head>
4 <title>HTML Forms</title>
5</head>
6<body>
7 <form action="/submit" method="POST">
8 <label for="first-name">First Name:</label>
9 <input type="text" id="first-name" name="first-name">
10 <button type="submit">Submit</button>
11 </form>
12</body>
13</html>
In the example above, we have a form with an input field for the user's first name. When the user enters text in the input field, the change
event is triggered, and we can capture the value using JavaScript.
Here's an example of how we can listen to the change
event and log the entered first name to the console:
1// JavaScript code
2const firstNameInput = document.getElementById('first-name');
3
4firstNameInput.addEventListener('change', (event) => {
5 const firstName = event.target.value;
6 console.log(`First Name: ${firstName}`);
7});
xxxxxxxxxx
const firstNameInput = document.getElementById('first-name');
firstNameInput.addEventListener('change', (event) => {
const firstName = event.target.value;
console.log(`First Name: ${firstName}`);
});