Brian
Brian

Reputation: 349

how to capture backspace key code in android browser - javascript?

I have a page made in pure HTML Javascript... I handle the keyup code and I need to get the key code, when key code == 8 (backspace) special task must be run... but if I open the page in android browser, chrome, or whatever... backspace doesn't return any key code...

I've made:

$( '.input-cell' ).bind( 'keyup', function( e ){

   var keycode =  e.keyCode ? e.keyCode : e.which;

   alert( keycode );

   if( keycode == 8 ) {
               .....
   }
});

The alert returns me all the keycodes but the backspace... is there any way to capture the backspace press event?

Upvotes: 4

Views: 11004

Answers (2)

Leo
Leo

Reputation: 1027

Another solution can be check for the length of the characters before, and after, if it has less than one character than before, then clearly it was a backspace that fired, in my case I was using only one input with one character and needed to go back to the previous input after hitting a backspace, for my case I only got also 0 and 229 within the android keyboard, so I did this:

$('input').on('keydown', function (e) {
    switch(e.keyCode){
        case 229:
        case 0:
             if($(this).val() == '')
                 $(this).prev().focus();
             break;
    }
});

The same can be achieved by checking the characters, of course this will only be in the case of a backspace in the android keyboard device, is just a workaround, hope it helps.

Upvotes: -1

Hamze Sheyikh Shoaei
Hamze Sheyikh Shoaei

Reputation: 823

input change event

$('#myinput').bind('input', function(){
    // code
});

backspace

$('#myinput').on('keypress', function() {
    //code
    }).on('keydown', function(e) {
        if (e.keyCode==8) {
            //code
        }
    });

Upvotes: 3

Related Questions