Đối tượng Input Button đại diện cho <input type="button">, <input type="submit"> hoặc <input type="reset">. Dùng để tạo nút bấm tùy chỉnh không có hành vi mặc định như submit/reset.
Tạo nút button động
var btn = document.createElement("INPUT");
btn.setAttribute("type", "button"); // hoặc "submit", "reset"
btn.setAttribute("value", "Nhấn tôi");
Các thuộc tính chính
| Thuộc tính | Mô tả |
|---|---|
| autofocus | Tự động focus khi tải trang. |
| defaultValue | Giá trị mặc định của thuộc tính value (chỉ đọc). |
| disabled | Vô hiệu hóa nút (không thể nhấp). |
| form | Tham chiếu đến form chứa nút (chỉ đọc). |
| name | Tên của nút (dùng khi submit form). |
| type | Loại nút: "button", "submit", "reset" (chỉ đọc). |
| value | Nhãn hiển thị trên nút (có thể thay đổi). |
Ví dụ: Tạo nút sao chép (replicate) chính nó
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
.btn {
display: block; margin: 10px auto;
background-color: #dc3545; color: white; border: 1px solid #dc3545;
padding: 10px; border-radius: 25px; width: 60%;
font-weight: bold; cursor: pointer;
}
.msg { font-weight: bold; font-size: 1.2rem; color: #ffc107; margin-top: 10px; }
</style>
</head>
<body>
<h1>Ví dụ Input Button Object</h1>
<input type="button" onclick="createReplica()" class="btn" value="Nhấn để nhân bản tôi">
<div id="msg" class="msg"></div>
<script>
function createReplica() {
var newBtn = document.createElement("INPUT");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("class", "btn");
newBtn.setAttribute("value", "Nhấn để nhân bản tôi");
newBtn.setAttribute("onclick", "createReplica()");
document.body.appendChild(newBtn);
}
</script>
</body>
</html>
Kết quả
Nút ban đầu:

Sau khi nhấn nhiều lần - các nút mới được tạo ra:

💡 So sánh:
<input type="button">: Nút tùy chỉnh, cần JS để xử lý.<input type="submit">: Gửi form (mặc định).<input type="reset">: Đặt lại form về giá trị ban đầu.<button>: Linh hoạt hơn (chứa HTML, icon, pseudo-elements).