George Chen
George Chen

Reputation: 89

How to prevent a semicolon from being entered into html text input, but allowing a colon?

I want to allow input such as 1:10, but not 1;10. However, : and ; both correspond to keyCode 186, so using keyCode to prevent the ; key from inputting into my input field does not work. I also researched into using charCodes, but charCodes don't have the ; or : values. Finally, I looked at ascii tables. They have semicolon and colon values. Is there any way for me to possibly use ascii tables to prevent the ; key from inputting into my textbox, but the : key to be allowed? Or is there another approach that will let me do this? I also thought about detecting two key inputs in a row, so that I could detect a shift key input, but that 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;
        }
    }
});

Upvotes: 5

Views: 4213

Answers (4)

Nikhil Arora
Nikhil Arora

Reputation: 162

Check the keycode and key both in if condition.

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

Upvotes: 0

Namaskar
Namaskar

Reputation: 2119

Like Rory said, you should be using on. Instead of checking the shiftKey, you can also just check the key property on the 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" />

Upvotes: 5

vishal
vishal

Reputation: 116

You just try e.keycode the keycode for :58 and ; 59. if you want any keycode for letter or Symbols you just type within text below mention 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>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

Firstly, don't use bind(). It was deprecated a long time ago. Use on() instead.

To fix your issue you need to detect if the shift key is held down, for which you can use the shiftKey property of the event:

$("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" />

Upvotes: 2

Related Questions