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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With