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

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>​

Need Your Help

Selenium: How to use stored value in a javascript comparison

javascript selenium

I've searched around for the answer to this and found lots of much

Convert an asp.net application to IIS7 integrated mode

asp.net iis-7 .net-2.0

What steps I need to perform in order to convert asp.net 2 application from IIS7 classic to integrated mode?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.