Remove all non-numeric characters in input field when inserting Javascript

I have html with multiple fields. One of the fields allows only numerical input. But now I want the user to execute all characters in this field, except for the numbers where they were deleted or deleted.

For example, custom paste:

$ 1 234 567 → 1234567 in the input field

1.234.567 → 1234567

1,234,567 → 1234567

etc.

+5
source share
3 answers

use regex.

<input id="inputBox" name="inputBox" />
<script type="text/javascript">
var inputBox = document.getElementById('inputBox');
inputBox.onchange = function(){
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
}
</script>

or you can use a timer to constantly check this field.

<input id="inputBox" name="inputBox" />
<input id="inputBox2" name="inputBox2" />
<script type="text/javascript">
var timer = new Array();
function checkFields(el){
    var inputBox = document.getElementById(el);
    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
    clearTimeout(timer[el]);
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
function timerFields(el){
    timer[el] = setTimeout((function(){ checkFields(el); }), 50);
};
timerFields('inputBox');
timerFields('inputBox2');
</script>
+11
source

try it

var regexp=/\D/g;
alert(("$1 234 567").replace(regexp,""));
+2
source
var f = function (s) { 
  var r = ''; 

  for (var i in s) {
    if ('0' <= s[i] && s[i] <= '9') {
      r += s[i]; 
    }
  }

  return r;
}

alert(f('123.234-234?345')); // 23234234345

But use regexp from another answer :)

0
source

All Articles