Reputation: 5761
The following function works well, however it currently stops pasting text and number. Is there a way of stopping only text inside the input?
var restrictInputToDigits = function(){
$('.digits').keypress(function(key) {
if(key.charCode < 48 || key.charCode > 57) return false;
});
$('.digits').bind('copy paste', function (e) {
e.preventDefault();
});
}
I would like digits to be pasted in as well.
Upvotes: 1
Views: 248
Reputation: 18891
$('.digits').on('change keyup paste', function(e){
$this = $(this);
$this.val($this.val().replace(/\D+/, ''));
if(e.charCode < 48 || e.charCode > 57){ e.preventDefault(); return false; }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="digits" value="1234">
Upvotes: 5
Reputation: 12039
First get the value of text field. Then replace all characters except number by empty character. This should help
$('.digits').on('change keyup',function(){
var value = $(this).val().toString().replace(/[^0-9]/g, '');
$(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" class="digits">
Upvotes: 6