Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all non-numerical characters in input field on paste event Javascript

I have a html with several fields. One of the field allows only numerical input. But now I want that when user performes paste into that field all characters, except numbers where stripped or deleted.

For example user paste:

$1 234 567 -> 1234567 in input field

1.234.567 -> 1234567

1,234,567 -> 1234567

and so on

like image 809
halofourteen Avatar asked Aug 21 '12 07:08

halofourteen


1 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 could use a timer to constantly check that 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>​
like image 155
Mihai Iorga Avatar answered Sep 30 '22 09:09

Mihai Iorga