ddeamaral
ddeamaral

Reputation: 1443

Trying to remove non numeric characters from textbox using jQuery

I'm trying to remove a character as it's typed/keyed up to test whether it's a number or not, if it is a number, keep it, if not, remove it. It can be more than one digit. for example, I type in a "d", it should be deleted from the textbox. I then type a "1", where it should stay in the textbox. I then type a 4 and it also stays so the textbox now reads "14". Then I type "g", which should be deleted. Then I type a "5" and now the text box reads 145. This is what I have so far.

   $("#txtTestNumbersOnlyRegex").keyup(function () {

            $("#txtTestNumbersOnlyRegex").val(function (index, value) {
                var keyPressed = value.substr(0, value.length - 1);
                var regEx = new RegExp("/^5$/");
                if(!regEx.test(keyPressed)) {
                    alert("true");
                    return value.substr(0, value.length - 1);
                }                   
            });      

        });            

Upvotes: 3

Views: 7930

Answers (3)

Joy Biswas
Joy Biswas

Reputation: 6527

You can intercept the values that are coming in and decide what to do, So it is better to have the keypress else your text gets replaced everytime and say if you are in middle of input val and you are editing caret will jump to the end in other cases

$("#txtTestNumbersOnlyRegex").keypress(function (event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if((keyCode>=65 && keyCode<=90) || (keyCode>=97 && keyCode<=122))
        return false;
    else return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id = txtTestNumbersOnlyRegex />

Upvotes: 1

Marko Gresak
Marko Gresak

Reputation: 8217

You can use regex to replace any non digits with empty space, although this will look a bit weird.

$('input').keyup(function() {
    $(this).val($(this).val().replace(/\D/, ''));
});

Full snippet:

$('input').keydown(function() {
        console.log($(this).val());
        $(this).val($(this).val().replace(/\D/, ''));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">


Or you could use input type="number" if you don't care about IE support.

Upvotes: 1

Neil Villareal
Neil Villareal

Reputation: 637

You might want to try this:

$("#txtTestNumbersOnlyRegex").keyup(function () { 
    var newValue = $(this).val().replace(/[^0-9]/g,'');
    $(this).val(newValue);    
 });  

You can try it here https://fiddle.jshell.net/aooh0gkz/

Upvotes: 4

Related Questions