9.1 Các sự kiện cơ bản của form
Để làm cho form hoạt động, cần hiểu và quản lý các sự kiện xảy ra khi người dùng tương tác với các thành phần của form. Dưới đây là phần giải thích chi tiết về các sự kiện cơ bản của form trong HTML, xử lý chúng bằng JavaScript và ví dụ sử dụng.
Trong HTML, form có thể tạo ra nhiều sự kiện khác nhau diễn ra khi người dùng tương tác với các thành phần của form như ô nhập liệu, nút bấm, checkbox và radio button. Các sự kiện chính của form bao gồm:
- submit — sự kiện gửi form
- reset — sự kiện đặt lại form
- focus — sự kiện khi một thành phần nhận được focus
- blur — sự kiện khi một thành phần bị mất focus
- change — sự kiện thay đổi giá trị của một thành phần trong form
- input — sự kiện khi nhập dữ liệu vào một thành phần của form
- select — sự kiện khi chọn văn bản trong một thành phần của form
9.2 Sự kiện submit
Sự kiện submit xảy ra khi form được gửi đi. Điều này thường xảy ra khi người dùng nhấn nút "Submit" trong form. Xử lý sự kiện này cho phép thực hiện kiểm tra dữ liệu trước khi gửi chúng lên server, ngăn chặn việc gửi form khi có lỗi nhập liệu và thực hiện các hành động khác.
Ví dụ xử lý sự kiện submit:
<form id="my-form" action="/submit" method="post">
<label for="username">Tên người dùng:</label>
<input type="text" id="username" name="username">
<button type="submit">Gửi</button>
</form>
const form = document.getElementById('my-form');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
if (username === '') {
alert('Vui lòng nhập tên người dùng.');
event.preventDefault(); // ngăn không cho gửi form
} else {
alert(`Tên người dùng đã nhận được: ${username}`);
event.preventDefault();
}
});
const form = document.getElementById('my-form');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username').value;
if (username === '') {
alert('Vui lòng nhập tên người dùng.');
event.preventDefault(); // ngăn không cho gửi form
}
});
9.3 Sự kiện reset
Sự kiện reset xảy ra khi form được đưa về trạng thái ban đầu. Thường thì điều này xảy ra khi người dùng nhấn nút "Reset". Xử lý sự kiện này có thể hữu ích để thực hiện các hành động bổ sung khi form được reset, như xóa thông báo lỗi.
Ví dụ xử lý sự kiện reset:
<div style="min-height: 220px">
<form id="my-form">
<label for="name">Name:</label>
<br>
<input type="text" id="name" name="name">
<br><br>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email">
<br><br>
<label for="password">Password:</label>
<br>
<input type="password" id="password" name="password">
<div style="margin-top: 10px">
<button id="btn" type="button">Đặt lại</button>
</div>
</form>
<p id="log"></p>
</div>
<form id="my-form">
<label for="name">Name:</label>
<br>
<input type="text" id="name" name="name">
<br><br>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email">
<br><br>
<label for="password">Password:</label>
<br>
<input type="password" id="password" name="password">
<div style="margin-top: 10px">
<button type="reset">Đặt lại</button>
</div>
</form>
<p id="log"></p>
const form = document.getElementById('my-form');
const btn = document.getElementById('btn');
const n = document.getElementById('name');
const e = document.getElementById('email');
const p = document.getElementById('password');
const log = document.getElementById('log');
document.addEventListener('DOMContentLoaded', () => {
n.value = "John";
e.value = "john@mail.com";
p.value = "qwerty";
});
btn.addEventListener('click', () => {
n.value = "";
e.value = "";
p.value = "";
log.textContent = 'Form đã được đặt lại!';
});
const form = document.getElementById('my-form');
const log = document.getElementById('log');
form.addEventListener('reset', function () {
log.textContent = 'Form đã được đặt lại!';
});
9.4 Sự kiện focus và blur
Sự kiện focus và blur xảy ra khi một phần tử của form nhận và mất focus tương ứng. Những sự kiện này thường được sử dụng để cải thiện sự tương tác giữa người dùng và form, ví dụ như hiển thị gợi ý hoặc thông báo lỗi.
Ví dụ xử lý sự kiện focus:
<div style="min-height: 55px">
<form id="my-form">
<label for="username">Tên người dùng:</label>
<input type="text" id="username" name="username">
<div id="username-hint" style="display: none;">
Bạn sẽ thấy gợi ý này khi focus vào ô nhập.
Nó sẽ hiển thị kể cả sau khi đổi focus.
</div>
</form>
</div>
<form id="my-form">
<label for="username">Tên người dùng:</label>
<input type="text" id="username" name="username">
<div id="username-hint" style="display: none;">
Bạn sẽ thấy gợi ý này khi focus vào ô nhập.
Nó sẽ hiển thị kể cả sau khi đổi focus.
</div>
</form>
const form = document.getElementById('my-form');
const usernameInput = document.getElementById('username');
const hint = document.getElementById('username-hint');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
usernameInput.addEventListener('focus', function (event) {
hint.style.display = 'block';
});
const usernameInput = document.getElementById('username');
const hint = document.getElementById('username-hint');
usernameInput.addEventListener('focus', function () {
hint.style.display = 'block';
});
Ví dụ xử lý sự kiện blur:
<div style="min-height: 55px">
<form id="my-form">
<label for="username">Tên người dùng:</label>
<input type="text" id="username" name="username">
<div id="username-error" style="display: none; color: red;">
Lỗi chỉ xuất hiện khi ô nhập trống sau khi đổi focus
</div>
</form>
</div>
<form id="my-form">
<label for="username">Tên người dùng:</label>
<input type="text" id="username" name="username">
<div id="username-error" style="display: none; color: red;">
Lỗi chỉ xuất hiện khi ô nhập trống sau khi đổi focus
</div>
</form>
const form = document.getElementById('my-form');
const usernameInput = document.getElementById('username');
const error = document.getElementById('username-error');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
usernameInput.addEventListener('blur', function (event) {
error.style.display = usernameInput.value === '' ? 'block' : 'none';
});
const usernameInput = document.getElementById('username');
const error = document.getElementById('username-error');
usernameInput.addEventListener('blur', function () {
error.style.display = usernameInput.value === '' ? 'block' : 'none';
});
9.5 Sự kiện input
Sự kiện input xảy ra mỗi khi giá trị của một phần tử form thay đổi, bất kể phần tử có mất focus hay không. Sự kiện này thường được sử dụng để kiểm tra dữ liệu người dùng ngay lập tức, ví dụ như khi validate các trường input theo thời gian thực.
Ví dụ xử lý sự kiện input:
<html lang="vi-VN">
<head>
<style>
input {
outline: none;
}
.valid {
border-color: green;
}
.invalid {
border-color: red;
}
.wrapper-valid::after {
content: "Email hợp lệ";
margin-left: 5px;
color: green;
}
.wrapper-invalid::after {
content: "Email không hợp lệ";
margin-left: 5px;
color: red;
}
</style>
</head>
<body>
<form id="my-form">
<label for="email">Email:</label>
<div id="wrapper">
<input type="email" id="email" name="email">
</div>
</form>
</body>
</html>
const form = document.getElementById('my-form');
const inputWrapper = document.getElementById('wrapper');
const emailInput = document.getElementById('email');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
emailInput.addEventListener('input', function () {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(emailInput.value)) {
inputWrapper.classList.add('wrapper-valid');
inputWrapper.classList.remove('wrapper-invalid');
emailInput.classList.add('valid');
emailInput.classList.remove('invalid');
} else {
inputWrapper.classList.add('wrapper-invalid');
inputWrapper.classList.remove('wrapper-valid');
emailInput.classList.add('invalid');
emailInput.classList.remove('valid');
}
});
const emailInput = document.getElementById('email');
const inputWrapper = document.getElementById('wrapper');
emailInput.addEventListener('input', function () {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(emailInput.value)) {
emailInput.classList.add('valid');
emailInput.classList.remove('invalid');
} else {
emailInput.classList.add('invalid');
emailInput.classList.remove('valid');
}
});
9.6 Sự kiện select
Sự kiện select được kích hoạt khi người dùng chọn văn bản trong một thành phần form, chẳng hạn như một ô input hoặc ô textarea. Sự kiện này có thể hữu ích để thực hiện các hành động khi chọn văn bản, ví dụ như hiển thị nút copy.
Ví dụ xử lý sự kiện select:
<div style="min-height: 55px">
<form id="my-form">
<label for="text-input">Nhập văn bản:</label>
<input type="text" id="text" name="text">
<div id="select-message"></div>
</form>
</div>
<form id="my-form">
<label for="text-input">Nhập văn bản:</label>
<input type="text" id="text" name="text">
<div id="select-message"></div>
</form>
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('my-form');
const textInput = document.getElementById('text');
const selectMessage = document.getElementById('select-message');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
textInput.addEventListener('select', function () {
selectMessage.textContent = 'Bạn đã chọn văn bản!';
});
});
document.addEventListener('DOMContentLoaded', function () {
const textInput = document.getElementById('text');
const selectMessage = document.getElementById('select-message');
textInput.addEventListener('select', function () {
selectMessage.textContent = 'Bạn đã chọn văn bản!';
});
});
9.7 Sự kiện change
Sự kiện change xảy ra khi giá trị của một phần tử trong form thay đổi, và người dùng rời khỏi phần tử đó (mất focus). Sự kiện này thường được dùng để kiểm tra các thay đổi trong các trường form, như dropdown list hoặc checkbox.
Ví dụ xử lý sự kiện change:
<form id="my-form">
<label for="color-select">Chọn màu:</label>
<select id="color-select" name="color">
<option value="red">Màu đỏ</option>
<option value="green">Màu xanh lá</option>
<option value="blue">Màu xanh dương</option>
</select>
</form>
document.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById('my-form');
const selectElement = document.getElementById('color-select');
form.addEventListener("submit", (event) => {
event.preventDefault();
});
selectElement.addEventListener('change', function () {
alert('Bạn đã chọn màu: ' + selectElement.value);
});
});
document.addEventListener('DOMContentLoaded', function () {
const selectElement = document.getElementById('color-select');
selectElement.addEventListener('change', function () {
alert('Bạn đã chọn màu: ' + selectElement.value);
});
});
GO TO FULL VERSION