I have this input that is to enter postal code but it is written in a way that only allows the entry of numbers and if you write letters it does not work, the problem is that it is written in the html and it looks horrible, I am trying to place the events on the side of the Js but I can't get them to work. What happens to them?
function alpha(e) {
var k;
document.all ? k = e.key : k = e.which;
return (k == 189 || (k >= 48 && k <= 57));
}
<input type="tel" name="zipcode" id="zipcode" class="form-control" placeholder="Zip Code" required onkeypress="return alpha(event);" oninput="javascript:
if(this.value.length>5){
var num_sf=this.value;
var num_cf=''
num_cf=num_sf.substring(0,5)
this.value=num_cf;
}" ontouchstart="this.removeAttribute('readonly');" onfocus="this.removeAttribute('readonly');" inputmode="tel" maxlength="5">
The code that I am using is this.
function alpha(e) {
var k;
document.all ? k = e.key : k = e.which;
return (k == 189 || (k >= 48 && k <= 57));
}
const INPUT_ZIPCODE = document.getElementById('zipcode');
if (INPUT_ZIPCODE) {
INPUT_ZIPCODE.addEventListener('touchstart', (e) => {
e.target.removeAttribute('readonly');
});
INPUT_ZIPCODE.addEventListener('focus', (e) => {
e.target.removeAttribute('readonly');
});
INPUT_ZIPCODE.addEventListener('input', (e) => {
if(e.target.value.length>5){
var num_sf=e.target.value;
var num_cf=''
num_cf=num_sf.substring(0,5)
e.target.value=num_cf;
}
});
INPUT_ZIPCODE.addEventListener('keypress', (e) => {
return alpha(e);
});
}
<input type="tel" name="zipcode" id="zipcode" class="form-control" placeholder="Zip Code" required inputmode="tel" maxlength="5">
What is horrible is a matter of taste, I like it more than the alternative that you propose.
You have 2 problems:
The alpha function is wrong. When this function takes the value of e.key, the if that follows it doesn't make sense. And this happens when you call it from the addEventListener. Take that value instead of taking the value of e.which I removed this function and put that condition inside the event
The addEventListener when it returns false doesn't cancel the event (like it does when it's in html) so you have to stop it by hand
On the other hand, maxlength already does the limiting of the number of characters, plus you remove the readonly attribute but you never added it in the first place. So it seems to me that your problem boils down to: