2

I am trying to filter user input by using a custom jQuery function :

$(document).ready(function(){
$('#afm').keypress(function(key){

    var len = $('#afm').val().length;
    console.log(key.charCode);

    if( key.charCode < 8   || (key.charCode > 8 && key.charCode < 48) || key.charCode > 57 && len < 9){ 

        $('#tip-afm').text("error");
        return false;
    }
    else
        $('#tip-afm').text("");
 })
})

Whenever i press backspace, console.log displays charCode as 0. As far as i know 8 is code assigned to backspace.. Am i doing something wrong? Do i have to change the code to handle backspace's code as 0?Or this may lead to errors in the future?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 2
    You should use `keyCode` instead of `charCode`. `console.log(event.keyCode); – Arnaud Gueras Feb 23 '16 at 13:58
  • 1
    What OS/Browser are you using ? Eg. firefox for android have `keyCode=0` to letters and backspace, in chrome for android `keyCode=229` – Yoplaboom Feb 23 '16 at 14:02
  • I am using Firefox..But how can i restrict user input independent of the browser being used? –  Feb 23 '16 at 14:03

4 Answers4

2

Use this to get the code of the pressed key

var code = e.keyCode || e.which;
drosam
  • 2,866
  • 3
  • 16
  • 18
2

Check chars using this:

key.which and key.keyCode

Szymon Pajka
  • 101
  • 8
2

The keypress event might not be fired when the users enters a backspace. Check this answer, you might want to use a keyupinstead. Check also my answer to another question: https://stackoverflow.com/a/30108293/2314737

Community
  • 1
  • 1
user2314737
  • 27,088
  • 20
  • 102
  • 114
  • I decided to do this by using charCode,it turns out to be the easiest solution,since i charCode is 0 for all browsers the page will support(firefox,chrome and explorer).Your jsfiddle helped me figuring out this.Any other idea/advice available is highly appreciated:) –  Feb 23 '16 at 14:19
1

You have to use jQuery.keyup() instead of jQuery.keypress() and use key.keyCode instead of key.charCode.

Code below:

$(document).ready(function(){
$('#afm').keyup(function(key){

    var len = $('#afm').val().length;
    console.log(key.keyCode);

    if( key.keyCode < 8   || (key.keyCode > 8 && key.keyCode < 48) || key.keyCode > 57 && len < 9){ 

        $('#tip-afm').text("error");
        return false;
    }
    else
        $('#tip-afm').text("");
 })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="afm">
<div id="tip-afm">

</div>
Damian Bartosik
  • 498
  • 6
  • 24