简体   繁体   中英

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/

You need to filter non-printable keypress events, in case the browser is firing them.

For instance, for backspace:

$('#num').keypress(function(e) {
  if(e.keyCode == 8) {
    return true;
  }
  $this = $(this);
  // etc.
}

Use the .keydown and you do not have to worry about checking whether backspace or not! because it will work with any key pressed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM