Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Đối tượng Input Number trong HTML DOM

Đối tượng Input Number đại diện cho <input type="number"> - cho phép nhập số với các điều khiển tăng/giảm (spinner) và validation tự động.

Tạo input number động

var numInput = document.createElement("INPUT");
numInput.setAttribute("type", "number");

Các thuộc tính chính

Thuộc tínhMô tả
autocompleteBật/tắt tự động hoàn thành.
autofocusTự động focus khi tải trang.
disabledVô hiệu hóa input.
defaultValueGiá trị mặc định ban đầu.
formForm chứa input (chỉ đọc).
listTham chiếu <datalist> gợi ý (chỉ đọc).
maxGiá trị lớn nhất cho phép.
minGiá trị nhỏ nhất cho phép.
nameTên trường form.
placeholderGợi ý nhập liệu (placeholder text).
readOnlyChỉ đọc (vẫn submit).
requiredBắt buộc nhập trước khi submit.
stepBước nhảy (mặc định 1).
typeLuôn là "number" (chỉ đọc).
valueGiá trị hiện tại (số).

Phương thức

Phương thứcMô tả
stepUp(n)Tăng giá trị lên n bước (mặc định 1 bước = step).
stepDown(n)Giảm giá trị xuống n bước.

Ví dụ: Tạo input number động (đã sửa code mẫu)

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; font-family: sans-serif; padding: 20px; }
        .btn {
            background-color: #dc3545; border: none; color: white;
            padding: 10px 20px; border-radius: 5px; cursor: pointer;
            font-size: 1rem; margin: 10px; display: inline-block;
        }
    </style>
</head>
<body>
    <h1>Ví dụ DOM Input Number Object</h1>
    <button onclick="createNumberField()" class="btn">Tạo input số</button>
    <script>
        function createNumberField() {
            var input = document.createElement("INPUT");
            input.setAttribute("type", "number");
            input.setAttribute("min", "0");
            input.setAttribute("max", "100");
            input.setAttribute("step", "1");
            input.setAttribute("value", "50");
            input.style.width = "200px";
            input.style.padding = "8px";
            document.body.appendChild(input);
        }
    </script>
</body>
</html>

Kết quả

Trước khi nhấn:

Đối tượng Input Number trong HTML DOM

Sau khi nhấn "Tạo input số":

Đối tượng Input Number trong HTML DOM

⚠️ Lưu ý: Input number **không cho phép** ký tự chữ (trừ e/E cho khoa học). Giá trị trả về qua .value là **string**, cần Number() hoặc valueAsNumber để lấy kiểu number.