I’m using this script to only allow my input text letters and numbers
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;
console.log("If 1");
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
console.log("if 2");
} else {
console.log("if 3");
this.value = "";
}
});
});
}
setInputFilter(document.getElementById("frm_nuevo_proveedor:j_idt35"), function(value) {
return /^[^\W_]+$/i.test(value);
});
My problem is that once I type the first value it doesn’t let me erase it anymore
So the first value won’t let me delete it.
>Solution :
When you attempt to remove the last character, the RegExp returns false because it is not set to accept blank strings. This causes the script to restore the oldValue, which would be that single letter.
The simplest fix seems to be updating the RegExp used as the filter. This should work for you, though I’m no expert on regular expressions so there may be a better way:
setInputFilter(document.getElementById("testEl"), function(value) {
return /(^$|^[^\W_]+$)/i.test(value);
});