Thuộc tính autofocus của Button trong HTML DOM liên quan đến thuộc tính autofocus của phần tử <button>. Thuộc tính button autofocus dùng để chỉ định xem một nút trên tài liệu HTML có nên nhận focus hay không khi trang tải.
Cú pháp
Thiết lập thuộc tính button autofocus
buttonObject.autofocus = true|false
Ở đây, true|false chỉ định xem nút input có nhận focus khi tải trang hay không.
- True - Nút input nhận focus
- False - Nút input không nhận focus
Ví dụ
Dưới đây là ví dụ cho thuộc tính autofocus của button HTML DOM:
<!DOCTYPE html> <html> <body> <button type="button" id="MyButton" autofocus>NÚT</button> <p>Click nút bên dưới để biết nút input trên có tự động nhận focus khi tải trang hay không</p> <button onclick="buttonFocus()">CLICK IT</button> <p id="Sample"></p> <script> function buttonFocus() { var x = document.getElementById("MyButton").autofocus; if(x == true) document.getElementById("Sample").innerHTML = "Nút input nhận focus khi tải trang"; else document.getElementById("Sample").innerHTML = "Nút input không nhận focus khi tải trang"; } </script> </body> </html>
Kết quả
Ví dụ này sẽ cho kết quả sau:

Khi click nút CLICK IT:

Giải thích ví dụ:
Nút với id “MyButton” và autofocus enabled:
<button type="button" id="MyButton" autofocus>NÚT</button>
Nút CLICK IT thực thi buttonFocus():
<button onclick="buttonFocus()">CLICK IT</button>
buttonFocus() lấy nút bằng getElementById(), lấy giá trị autofocus (Boolean) gán cho x. Dùng câu điều kiện kiểm tra autofocus true/false hiển thị văn bản phù hợp trong <p> id “Sample”:
function buttonFocus() { var x = document.getElementById("MyButton").autofocus; if(x == true) document.getElementById("Sample").innerHTML = "Nút input nhận focus khi tải trang"; else document.getElementById("Sample").innerHTML = "Nút input không nhận focus khi tải trang"; }