Baptiste Arnaud Baptiste Arnaud - 3 months ago 13
jQuery Question

on keypress jquery function, backspace doesn't work

I implemented a function that add white space like so automatically :

+33 6 XX XX XX XX


or

06 XX XX XX XX


Here is the script :

$('#num').keypress(function(){
$this = $(this);
//remove whitespaces to calculate the length of the string
$val = $this.val().replace(/\s+/g, '');
//if it's the case '+33 6 XX XX XX XX
if ($val.toLowerCase().indexOf("+") >= 0 | $val == "")
{
if($val.length == 3){
$this.val($this.val() + " ");
}else if($val.length == 4){
$this.val($this.val() + " ");
}else if ($val.length >= 5 && ($val.length)%2 == 0){
$this.val($this.val() + " ");
}
}else{
if (($val.length)%2 == 0){
$this.val($this.val() + " ");
}
}

});


It works perfectly on chrome but on firefox i can't backspace the input.. Any ideas ?

Here is a jsfiddle to illustrate :

https://jsfiddle.net/jd1mwp3p/

Answer

There are 2 things to think about here.

The first one is that different browsers handle keypress,keyup, keydown, differently. In particular when it comes to non printable chars, such as backspace, some browsers fire the keypress event and some don't. Firefox does, and Chrome doesn't.

Now if you look at your code, you don't take in consideration backspace. Indeed what you do is adding a space if there is no + sign and the value is even:

else{
         if (($val.length)%2 == 0){
            $this.val($this.val() + " ");
        }
    }

and you again add a space if the value is 3 4 or 5 chars long when there is a + or the value is empty:

if ($val.toLowerCase().indexOf("+") >= 0 | $val == "")
    {
     if($val.length == 3){
            $this.val($this.val() + " ");
        }else if($val.length == 4){
            $this.val($this.val() + " ");
        }else if ($val.length >= 5 && ($val.length)%2 == 0){
            $this.val($this.val() + " ");
        }
    }

So. Chrome ignores your keypressed event and just deletes the chars, firefox calls your event and you do not handle backspace.