George Chen George Chen - 1 year ago 46
HTML Question

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;
}
}
});

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download