Thuộc tính autofocus của <input type="checkbox"> cho phép trả về hoặc thiết lập việc checkbox có tự động nhận focus khi trang tải xong hay không.
Cú pháp
Lấy giá trị:
checkboxElement.autofocus
Thiết lập giá trị:
checkboxElement.autofocus = true | false
Ví dụ: Checkbox có autofocus
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
input[type="checkbox"] { width: 24px; height: 24px; accent-color: #dc3545; }
button {
background-color: #dc3545; color: white; border: none;
padding: 8px 16px; border-radius: 20px; cursor: pointer;
margin: 5px; font-weight: bold;
}
</style>
</head>
<body>
<h1>Ví dụ autofocus Checkbox</h1>
<p>Bạn cần giúp đỡ không?</p>
<input type="checkbox" id="helpCheckbox" autofocus>
<br><br>
<button onclick="checkYes()">Có</button>
<button onclick="checkNo()">Không</button>
<script>
function checkYes() {
document.getElementById("helpCheckbox").checked = true;
}
function checkNo() {
document.getElementById("helpCheckbox").checked = false;
}
</script>
</body>
</html>
Kết quả
Khi tải trang, checkbox tự động có focus (viền đỏ):

Nhấn "Có" để tích, "Không" để bỏ tích:


✅ Mẹo: Chỉ nên dùng
autofocus cho **một** phần tử trên trang. Nếu nhiều phần tử có autofocus, trình duyệt sẽ focus vào phần tử đầu tiên trong luồng DOM.