Reputation:
The desired effect is such that when the user types in any character that is not a letter or a number, that character is immediately removed; thus causing the text cursor to not advance.
After already trying to look for solutions online myself, here is what I have so far:
<input type="text" id="job-name" maxlength="20" pattern="[a-zA-Z0-9]+" style="width:200px; text-align:center;">
document.getElementById('job-name').addEventListener('keydown', function () {
if (!document.getElementById('job-name').validity.valid) {
var text = document.getElementById('job-name').value;
text = text.slice(0,-1);
document.getElementById('job-name').value = text;
}
});
The problem is that the check of the 'valid' attribute is thus far always true and never false, regardless of the character typed in, for some reason. My expectation was that whenever the character that was just typed in does not conform to the pattern, the 'valid' should return false; otherwise, it is true.
Upvotes: 0
Views: 268
Reputation: 33726
Use the event input
to accomplish that:
This approach uses the regex /[^a-z0-9]+/i
.
Basically, for every input char/text, the handle will replace with empty the invalid char.
document.getElementById('job-name').addEventListener('input', function(e) {
this.value = this.value.replace(/[^a-z0-9]+/i, '');
})
<input type="text" placeholder='Paste text, drag text or type text' id="job-name" maxlength="20" style="width:400px; text-align:center;">
Upvotes: 1
Reputation: 3675
Try using the input
event instead of keydown
.
document.getElementById('job-name').addEventListener('input', function () {
if (!document.getElementById('job-name').validity.valid) {
var text = document.getElementById('job-name').value;
text = text.slice(0,-1);
document.getElementById('job-name').value = text;
}
});
Upvotes: 0