I have for the following input:

onkeyup="this.value = this.value.replace (/\D/, '')" 

How to make, in addition to numbers it was possible to enter also the + sign?

  • one
    Are you sure this is enough? If the user enters "12 + 34" - is this normal? - VladD

2 answers 2

 onkeyup="this.value = this.value.replace (/[^0-9+]/, '')" 
  • That it was impossible to enter characters, for example, while holding the ттттт key, or through CTRL+V You need to add the modifier g - onkeyup="this.value = this.value.replace (/[^0-9+]/g, '')" - Maxim Belov

As an option.
Disadvantage: any characters can be entered via CTRL+V

 function cislo(){ if (event.keyCode != 43 && event.keyCode < 48 || event.keyCode > 57) event.preventDefault(); } 
 <input type="text" onKeyPress="cislo()"> 

Another option - the characters can not be entered even through CTRL+V

 document.oninput = function() { var input = document.querySelector('.input-0'); input.value = input.value.replace (/[^\+\d]/g, ''); } 
 <input type="text" class="input-0"> 

  • 2
    Like the TS asks the numbers and +. I managed to enter: 123 /&*-+"! . - 0xdb
  • Corrected the mistake. - Maxim Belov
  • full replacement of the value in the handler is not a good idea - Grundy
  • @Grundy - what's a good idea? Sorry for your curiosity .. - Maxim Belov
  • just show the error. - Grundy