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">