user3065931
user3065931

Reputation: 531

Prevent certain characters being typed into text input

I have read a number of questions similar to this. And some of the solutions work. However the only way I can get this to work is to allow the character to be typed, and then remove it. It looks messy and feels hacky.

How do I prevent the character from being typed in the first place?

Demo: https://jsfiddle.net/jf8bqp5z/

HTML:

<input type="text" name="test" id="test"/>

jQuery:

$('#test').keyup(function(e){
    var $this = $(this);
    var val = $this.val();

    if( val.indexOf('.') ){
        val = parseInt(val);
        $this.val(val);
        e.preventDefault();
    }
});

SOLUTION

Actually really simple. I've switched the keyup event for keydown and just look for the keyCode:

$('#test').keydown(function(e){
    var $this = $(this);
    var val = $this.val();

    if( e.keyCode === 65 ){     //Here provide the JavaScript event keycode of the key to prevent being typed.
        e.preventDefault();
    }
});

Demo : https://jsfiddle.net/j80hryvm/

Note : You can get the keycode from http://keycode.info/

Upvotes: 2

Views: 2497

Answers (2)

simon
simon

Reputation: 46

I found this answer, it never prints the characters you don't want printed.

You can accomplish this by preventing the keyPress event from occurring for non-numeric values

e.g (using jQuery)

$('.input-selector').on('keypress', function(e){
  return e.metaKey || // cmd/ctrl
    e.which <= 0 || // arrow keys
    e.which == 8 || // delete key
    /[0-9]/.test(String.fromCharCode(e.which)); // numbers
})

This accounts for all different types of input (e.g. input from the number pad has different codes than the keyboard) as well as backspace, arrow keys, control/cmd + r to reload etc

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

You might need to return false:

$('#test').keyup(function(e){
    var $this = $(this);
    var val = $this.val();

    if( val.indexOf('.') ){
        val = parseInt(val);
        if (val == NaN)
            return false;
        $this.val(val);
        e.preventDefault();
    }
});

Upvotes: 0

Related Questions