JSFiddle - React, Tailwind, and code Playground
by uiwwnw
HTML
<input type="text" id="input1" class="input" data-max-length="12" data-comma="5">
<input type="text" id="input2" class="input" data-decimal="true">
<input type="text" id="input3" class="input" data-fake-dom="true" data-max-length="12">
JavaScript
var Numberic = (function() {
function Numberic(e) {
this.ele = typeof e === 'string' ? document.querySelector(e) : e;
this.ctrlEle = this.ele;
this.option = {
comma: this.ele.dataset.comma || 3,
fakeDom: this.ele.dataset.fakeDom || false,
decimal: this.ele.dataset.decimal || false,
maxLength: this.ele.dataset.maxLength || 20,
};
if (this.option.fakeDom) {
this.ele.style.display = 'none';
this.fakeDom();
this.ctrlEle = this.fakeEle;
}
this.ctrlEle.onkeydown = this.onkeydown.bind(this);
this.ctrlEle.onkeyup = this.debounce.bind(this, this.onkeyup.bind(this), 50);
}
Numberic.prototype.fakeDom = function() {
this.fakeEle = this.ele.cloneNode();
this.fakeEle.style.display = '';
this.fakeEle.id = 'fake_' + this.ele.id;
this.ele.parentNode.appendChild(this.fakeEle);
};
Numberic.prototype.onkeydown = function(e) {
if (e.key.match(/[0-9]/)) {
if (!this.length()) {
return false;
}
} else if (
(this.option.decimal) && (!this.hasDecimal ? e.key === '.' : false) ||
e.keyCode === 37 ||
e.keyCode === 38 ||
e.keyCode === 39 ||
e.keyCode === 40 || //상우하자
e.keyCode === 16 || //shift
e.keyCode === 36 || //home
e.keyCode === 35 || //end
e.keyCode === 9 || // tab
e.keyCode === 8 || // backspace
e.keyCode === 46 || // delete
e.ctrlKey && e.keyCode === 65 || // c + a
e.ctrlKey && e.keyCode === 67 || // c + c
e.ctrlKey && e.keyCode === 86 // c + v
) {} else {
return false;
}
};
Numberic.prototype.length = function() {
var string = String(this.getValue());
if (this.option.maxLength && this.option.maxLength <= string.length) {
return false;
}
return true;
};
Numberic.prototype.onkeyup = function(e) {
if (this.option.fakeDom) {
this.setValue(e.target.value);
}
this.setDisplay(e.target.value);
};
...