JQuery – Remove All Characters Except Digits

Here’s a fun snippet of code. It removes any character that is not a digit from a form field, as they’re typing it. Great for stripping down phone numbers.

$('#phone').keydown(function(){
    var self = $(this);
    var removedText = self.val().replace(/\D/, '');
    self.val(removedText);
});

Same thing, but do it when the field loses focus.

$('#phone').keydown(function(){
    var self = $(this);
    var removedText = self.val().replace(/\D/, '');
    self.val(removedText);
});

Leave a Reply

Your email address will not be published. Required fields are marked *