Hướng dẫn how do i make textbox input only numbers in html? - làm cách nào để tạo hộp văn bản chỉ nhập số trong html?

Bài đăng này sẽ thảo luận về cách hạn chế hộp văn bản đầu vào HTML để chỉ cho phép các giá trị số.

1. Sử dụng

Giải pháp tiêu chuẩn để hạn chế người dùng chỉ nhập các giá trị số là sử dụng các phần tử của số loại. Nó đã xác nhận tích hợp để từ chối các giá trị phi hình số. Điều này được thể hiện dưới đây:


Nhập tiền lương của bạn:for="salary">Enter your salary:

type="number"id="salary"name="salary">


Chỉnh sửa trong JSfiddle

2. Sử dụng thuộc tính pattern

Ngoài ra, bạn có thể sử dụng thuộc tính mẫu để chỉ định biểu thức chính quy sẽ phù hợp với đầu vào được cung cấp.

Việc sử dụng thuộc tính mẫu được thể hiện dưới đây. Nếu các giá trị chứa các ký tự không chữ số, phần tử sẽ khớp với các lớp giả CSS.

HTML


Nhập tiền lương của bạn:for="salary">Enter your salary:

type="text"id="salary"name="salary" pattern="[0-9]+">

Chỉnh sửa trong JSfiddle


2. Sử dụng thuộc tính pattern{

    border:3pxsolidred;border:3pxsolid red;

Ngoài ra, bạn có thể sử dụng thuộc tính mẫu để chỉ định biểu thức chính quy sẽ phù hợp với đầu vào được cung cấp.


Chỉnh sửa trong JSfiddle

2. Sử dụng thuộc tính pattern

Ngoài ra, bạn có thể sử dụng thuộc tính mẫu để chỉ định biểu thức chính quy sẽ phù hợp với đầu vào được cung cấp.oninput property to processes input events on the elements. To restrict the user to enter only numeric values, you can do like:

HTML


Nhập tiền lương của bạn:for="salary">Enter your salary:

type="text"id="salary"name="salary"

Chỉnh sửa trong JSfiddleoninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />


Chỉnh sửa trong JSfiddle

2. Sử dụng thuộc tính pattern

Ngoài ra, bạn có thể sử dụng thuộc tính mẫu để chỉ định biểu thức chính quy sẽ phù hợp với đầu vào được cung cấp.

Việc sử dụng thuộc tính mẫu được thể hiện dưới đây. Nếu các giá trị chứa các ký tự không chữ số, phần tử sẽ khớp với các lớp giả CSS.

HTML :)


Lưu ý: Đây là một câu trả lời cập nhật. Nhận xét dưới đây Tham khảo một phiên bản cũ lộn xộn với các mã hóa. This is an updated answer. Comments below refer to an old version which messed around with keycodes.

JavaScript

Hãy tự mình thử trên jsfiddle.

Bạn có thể lọc các giá trị đầu vào của văn bản với hàm

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");
1 sau (hỗ trợ sao chép+dán, kéo+thả, phím tắt, hoạt động menu ngữ cảnh, khóa không có khả năng, vị trí chăm sóc, bố cục bàn phím khác nhau, thông báo lỗi tính hợp lệ và thông báo lỗi hợp lệ và Tất cả các trình duyệt kể từ IE 9):

// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
    textbox.addEventListener(event, function(e) {
      if (inputFilter(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          this.classList.remove("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        this.classList.add("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  });
}

Bây giờ bạn có thể sử dụng chức năng

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");
1 để cài đặt bộ lọc đầu vào:

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");

Áp dụng phong cách ưa thích của bạn vào lớp lỗi đầu vào. Đây là một gợi ý:

.input-error{
  outline: 1px solid red;
}

Xem bản demo JSFiddle để biết thêm các ví dụ bộ lọc đầu vào. Cũng lưu ý rằng bạn vẫn phải thực hiện xác thực phía máy chủ!must do server side validation!

TYPEXTRIPT

Dưới đây là một phiên bản TypeScript của điều này.

function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
    ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
        textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
            if (inputFilter(this.value)) {
                this.oldValue = this.value;
                this.oldSelectionStart = this.selectionStart;
                this.oldSelectionEnd = this.selectionEnd;
            } else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
                this.value = this.oldValue;
                if (this.oldSelectionStart !== null &&
                    this.oldSelectionEnd !== null) {
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                }
            } else {
                this.value = "";
            }
        });
    });
}

jQuery

Ngoài ra còn có một phiên bản jQuery của điều này. Xem câu trả lời này.

HTML 5

HTML 5 có giải pháp gốc với (xem thông số kỹ thuật), nhưng lưu ý rằng hỗ trợ trình duyệt khác nhau:

  • Hầu hết các trình duyệt sẽ chỉ xác thực đầu vào khi gửi biểu mẫu và không phải khi nhập.
  • Hầu hết các trình duyệt di động không hỗ trợ các thuộc tính
    setInputFilter(document.getElementById("myTextBox"), function(value) {
      return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
    }, "Only digits and '.' are allowed");
    
    4,
    setInputFilter(document.getElementById("myTextBox"), function(value) {
      return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
    }, "Only digits and '.' are allowed");
    
    5 và
    setInputFilter(document.getElementById("myTextBox"), function(value) {
      return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
    }, "Only digits and '.' are allowed");
    
    6.
  • Chrome (phiên bản 71.0.3578.98) Vẫn cho phép người dùng nhập các ký tự
    setInputFilter(document.getElementById("myTextBox"), function(value) {
      return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
    }, "Only digits and '.' are allowed");
    
    7 và
    setInputFilter(document.getElementById("myTextBox"), function(value) {
      return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
    }, "Only digits and '.' are allowed");
    
    8 vào trường. Cũng xem câu hỏi này.
  • Firefox (phiên bản 64.0) và Edge (EdgeHTML phiên bản 17.17134) vẫn cho phép người dùng nhập bất kỳ văn bản nào vào trường.

Hãy tự mình thử trên w3schools.com.