3

I have a function that allow input field to receive numbers and the decimal point. How can I allow the backspace key as well ?

function verifierCaracteres(event) {

  var keyCode = event.which ? event.which : event.keyCode;
  var touche = String.fromCharCode(keyCode);

  var champ = document.getElementById('mon_input');

  var caracteres = '.0123456789';

  if(caracteres.indexOf(touche) >= 0) {
    champ.value += touche;
  }

}

And my HTML:

<input type="text" name="Patient_Amount" id="mon_input" onkeypress="verifierCaracteres(event); return false;"/>
Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
Diasline
  • 625
  • 3
  • 32
  • Similar to http://stackoverflow.com/questions/9906885/detect-backspace-and-del-on-input-event – le_m Jun 11 '16 at 00:43

1 Answers1

4

Use keyCode == 8 in your validation. 8 is the keycode for backspace.

Really, this is a job for regex and replace. That is how I typically go about this process. Here is an example.

function verifierCaracteres() {
    var inputEle = document.getElementById("mon_input");
    var value = inputEle.value;
    inputEle.value = value.replace(/([^0-9\.])+/g,'');
}

This will remove all characters from input that are not 0-9 or .

Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87