I\'m trying to make a date textbox on my blog, and the date is only numbers. I don\'t want anybody making a mistake typing a letter. Is there any way to limit the characters
You should use this function to set input filters on various DOM
elements including textarea
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
Then you simply set the filter, like that:
setInputFilter(document.getElementById("textarea_id"), value => {
return /^\d*$/.test(value); // Allow digits and '.' only, using a RegExp
});