There is a text field, I want to make it so that you can drive in only numbers.

Found an example of how to do it here .

But there is a problem: I have different keycode keys.

For example n = 102, and should be 78.

Question: why so? Maybe it all depends on the encoding / layout? Thanks for the help.

  • 2
    I do not know why you need the key n. Your task in solving is greybutton
  • Fine. Condition: if ((event.shiftKey || (event.keyCode <48 || event.keyCode> 57)) && (event.keyCode <96 || event.keyCode> 105)) {// && (event.keyCode < 96 || event.keyCode> 105)} event.preventDefault (); I press the b key, she returns me the keycode 98, and she counts my number! For example, I wrote, I basically have all the other keycodes. - MiXaiL
  • <input type="number" /> not tried? - Darth
  • this is html5, i need i7 support - MiXaiL
  • Just checked the keycode here - 78 in both layouts. Which browser do you have 102 in? Maybe use e.which ? - Surfin Bird

1 answer 1

Yes, the shift and hold shift key affects keyCode. It is better to use the which property, since in firefox, keyCode returns zero.

Here is an example.

 var inp = document.getElementsByTagName("input")[0]; inp.addEventListener("keypress", function(event) { if (event.which < 48 || event.which > 57) { event.preventDefault(); } }); 
 <input type="text" placeholder="Только цифры"> 

Also as an option you can use the mask - Masked Input Plugin

Example

 jQuery(function($){ $("#digits").mask("999999999",{placeholder:" "}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script> <input type="text" id="digits" placeholder="Только цифры"> 

But you need to specify the number of characters to enter.

Try these options. Should work. It is difficult to say that you have, without examples.