How to prevent semicolon input in html text input but colon resolution?

I want to allow input, for example 1:10, but not 1; 10. However: and; both correspond to keyCode 186, so using keyCode to prevent; The key to enter my input field does not work. I also studied the use of charCodes, but charCodes does not; or: values. Finally, I looked at the tables with shares. They have a comma and a colon. Is there a way for me to possibly use ascii tables to prevent; The key to enter in the text box, but is there a key :? Or is there another approach that will allow me to do this? I also thought about finding two key inputs in a line so that I can detect the switch key input, but this seems like a dirty solution.

$("input.form-1").bind({ keydown: function(e) { if(e.which ===186) { //trying to disallow semicolons, which also disallows colons return false; } } }); 
+5
source share
4 answers

As Rory said, you should use on . Instead of checking shiftKey, you can also just check the key property on an event. MDN KeyboardEvent.key

 $("input.form-1").on({ keydown: function(e) { if(e.key === ";") { // disallow semicolon return false; } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="form-1" type="text" /> 
+5
source

First, do not use bind() . It has been deprecated a long time ago. Use on() instead.

To fix your problem, you need to determine if the shift key is held down, for which you can use the event's shiftKey property:

 $("input.form-1").on({ keydown: function(e) { if (!e.shiftKey && e.which === 186) { return false; } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="form-1" type="text" /> 
+2
source

You just try the e.keycode key code for : 58 and ; 59. if you want any code for letters or symbols you entered only in the text below, specify the code.

 <html> <body> <input type="text" size="40" onkeypress="myFunction(event)"> <p id="demo"></p> <script> function myFunction(event) { var x = event.keyCode; document.getElementById("demo").innerHTML = x; } </script> </body> </html> 
+1
source

Check the key code and click both in the if condition.

 $("input.form-1").on({ keydown: function(e) { if(e.key === ";") { // disallow semicolon return false; } } }); 
0
source

Source: https://habr.com/ru/post/1270221/


All Articles