Thứ Ba, 23 tháng 6, 2015

Nhập duy nhất số vào textbox

Sau đây là cách chỉ cho nhập duy nhất số vào textbox. Với cách này thì tránh được cả việc Copy-> Paste.
Lưu ý: trong các sự kiện onkeypress và onkeyup tham số bên trong phải chính xác là 'event'.

HTML:

<input type="text" id="txtPhone" maxlength="15" class="k-textbox" disabled onkeypress="dataSupply.NumberOnly(event)" onkeyup="dataSupply.NumberOnlyKeyup(event)" />

JavaScript:

DataSupply.prototype.NumberOnly = function (e) {
    var regex = new RegExp("^[0-9]+$");
    var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (e.keyCode != 8 && !regex.test(key)) {
        e.preventDefault();
        return false;
    }
};

//chỉ cho nhập số
DataSupply.prototype.NumberOnlyKeyup = function (e) {
    $(e.currentTarget).val($(e.currentTarget).val().replace(/[^0-9]/g, ''));
};

var dataSupply = new DataSupply();

Không có nhận xét nào:

Đăng nhận xét