2

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/

Munawir
  • 3,346
  • 9
  • 33
  • 51
user3065931
  • 531
  • 7
  • 20
  • This will probably not handle the case where a user pastes something into the input field... In order to catch that you would have to constantly re-check the contents - probably with a `settimeout`... – Lix Aug 13 '15 at 12:21
  • 1
    I would just use the [`pattern`](http://www.w3.org/TR/html5/forms.html#the-pattern-attribute) HTML attribute and let the browser handle marking the input as invalid. – dsh Aug 13 '15 at 12:22
  • @dsh that will only mark as invalid when I try and submit. I would like to prevent it from being entered in the first place. – user3065931 Aug 13 '15 at 12:52
  • @user3065931 It will mark as invalid as soon as it is invalid (which is when the input is entered, it does not wait until the submit). It is true that it doesn't prevent the input from appearing in the first place. – dsh Aug 13 '15 at 12:59

2 Answers2

1

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

Community
  • 1
  • 1
simon
  • 46
  • 1
  • 5
0

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();
    }
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252