How can I not allow a character to be typed in the textbox, with javascript / jquery?


I have a Textbox:

<input type="text" name="indice" class="number">

I wanted it when someone typed a comma in this Textbox to block it from appearing in Textbox.

How to do this in the best way?

I would not want it if the person kept the comma pressed, it was appearing in the Textbox and then it was deleted, it was the most I could do.

asked by Joao Paulo 15.01.2014 в 18:24

4 answers


If your goal is to prevent not just being typed , but that it be used as a value anyway (eg copy and paste) I suggest listening to the input property and adjusting the value according to your rule (in this case, delete the commas):

$('input').on("input", function(e) {
    $(this).val($(this).val().replace(/,/g, ""));

Example in jsFiddle. In some older browsers, you may also need to hear by propertychange (but I believe which input is widely supported).

That way, it does not matter if the comma was typed on the "normal" keyboard, on the numeric keypad, Ctrl + C Ctrl + V or even Right-click and "paste". The value will be kept without the comma in all cases, and no visual glitch will occur.

P.S. See also this question I did some time ago in SOEN, for more details.

answered by 15.01.2014 / 18:55

You probably tried to intercept the key in the keyup event. If you use keydown , the comma does not appear.

Example in jQuery:

$('input').keydown(function(e) {
    if(e.which === 188 || e.which === 110) { // 188 é vírgula e 110 virgula do teclado numérico
        return false;   
        // ou:
        // e.preventDefault();

Demo on jsfiddle .

answered by 15.01.2014 в 18:27

@bfavaretto's answer directly answers the question, but as I said, I would not use a character filter of this type to prevent unwanted input.

This can be easily circumvented, even unconsciously (unintentionally), if the user copies a text and paste it into the

answered by 15.01.2014 в 18:58

A very simple way would simply be to disable the input using the disabled property ( <input name="" value="" disabled /> ). This way you can manipulate the value of this field and does not allow the user to enter anything through the keyboard.

answered by 14.05.2014 в 04:25