Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
});
like image 359
George Chen Avatar asked Jul 26 '17 13:07

George Chen


People also ask

Does HTML need semicolon?

They are required by the XHTML standard. (Semicolons is optional in the ECMA standard) 2. They give structure to your code, they says something about where the tags end.

How do you stop character input in HTML?

The typical way to prevent input of certain characters is to listen to the keydown event, check the character that is being input, then use event. preventDefault() to stop the input from occurring.

Can you use a colon and semicolon in the same sentence?

Colons and semicolons can be used in the same sentence, but they are each used for different purposes. Examples: I have lived in many large cities: Baltimore, Maryland; Dallas, Texas; and Miami, Florida.

What is the use of colon and semicolon in HTML?

The colon goes after a property and before the value, and the semi-colon is at the end of a statement. So for CSS like color: red; color is the property and red is the value. – Nikos M.


1 Answers

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" />
like image 185
Namaskar Avatar answered Sep 28 '22 11:09

Namaskar