Search code examples
javascriptonkeypress

js backspace and counting how many digits


i have this code for counting how many digits where entered

var tnnod=0;
function telephone(e) {
    if (tnnod<10) {
        var key;
        var keychar;

        if (window.event) {
            key = window.event.keyCode;
        }
        else if (e) {
            key = e.which;
        }
        else {
            return true;
        }
        keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
    tnnod+=1;
   return true;
}
else if (keychar == "-") { 
  return true;
}
else
   return false;
}
    else
        return false
}

but how do i remove 1 from the counter each time the backspace was hitted and the char that was deleted was a digit and not "-"

i have tried getting the key == 8 to do something but hitting the backspace doesn't really return anything for some reason

what can be the problem?


Solution

  • You don't have to detect specifically the backspace keypress. Try this:

    var tn_count = 0;
    function telephone(ev) {
      var el = document.getElementById("telephone_number");
    
      if(tn_count < 10) {
        var key, keychar;
        if(window.event) {
          key = window.event.keyCode;
        } else {
          key = ev.which;
        }
    
        keychar = String.fromCharCode(key);
      }
    
      if(!keychar.match(/\d|-/)) {  // only allow digits or "-"
        return false;
      }
    
      // clean up any non-digit chars that get in here somehow
      el.value = el.value.replace(/[A-Za-z]+/, '');
      tn_count = el.value.replace("-",'').length; // get the digit length
      return true;
    }
    

    The basic difference here is that instead of adding 1 every time the key is pressed, just updated tn_count to be the total count of all digit characters in the field. You can probably do some more cleanup just to be safe, but this should get you started.