Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 666
Baptiste Arnaud Avatar asked Dec 10 '25 06:12

Baptiste Arnaud


1 Answers

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.
}
like image 179
Arnauld Avatar answered Dec 12 '25 20:12

Arnauld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!