I have a form fill function in JavaScript that allows me to just enter numbers in a text box.
The problem is that it only works on computers and not on mobile devices.
function validarNumero(e) {
tecla = (document.all) ? e.keyCode : e.which;
if (tecla==8) return true;
patron =/[0-9]/;
te = String.fromCharCode(tecla);
return patron.test(te);
}
And in the HTML code part
<input type="text" id="txtNumero" maxlength="10" onkeypress="return validarNumero(event)">
If you can't make use of HTML5 and CSS3 then perhaps the most portable is to capture the events
keyup
andchange
to remove the numbers from the form field as follows:The reason is the complexity of keystrokes that you must filter to maintain compatibility with everything (mobile devices, copy/paste, hover, select part of the text, etc).
You can find more information about the keyboard codes in the documentation .
I personally would keep a hybrid version that could make use of HTML5 capabilities if they are present.
I keep the HTML5 + CSS3 version in the change history.
You should use the
number
input type as long as you don't need to support devices older than those listed in the caniuse table .UPDATE
Since you can't use HTML5, you could try this function:
I propose 2 solutions.
Use:
With this you get the numeric keypad to appear on the mobile. This has pros and cons.
On the one hand, you save validations and you have a more protected data entry. On the other hand, you cannot put a zero in front of '0898' for example, it would eliminate the 0. This is a problem if they are postal codes, telephone numbers, etc...
Another solution is to use:
This is HTML5 validation and works the same as required , minlength , maxlength , etc.
The example above validates that it is a string of between 7 and 15 digits where there can only be characters between 0-9 (it works very well for me for a first phone validation)
This is just an example, you can use any regular expression that works for you.
I don't know how to improve your javascript code but you could keep this option for desktop and use one of these options for mobile.