Developer
Developer

Reputation: 1437

Replace commas in a input field if only number is entered but not text : in the text field

i have a running code for removing comma in the text field, but i need to remove comma only when the entered value is number then comma should be removed, but not for text

Code :

JS :
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    $(function(){
        $("#textField").on('keyup', function(){
            this.value=this.value.replace(/,/g, "");
        });
    });
</script>      

HTML : 
<input type="text" id="textField" placeholder="" value="" />

Fiddle Here

Upvotes: 3

Views: 5008

Answers (4)

Paramesh Korrakuti
Paramesh Korrakuti

Reputation: 2067

Try this, no need to import jQuery also, working fine in all the browsers.

<input type="text" id="textField" placeholder="" value="" onkeyup="this.value = this.value.replace(/,/g, '')"/>

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use isNaN() method for checking it is a number or not

<script>
    $(function(){
        $("#textField").on('keyup', function(){
            if(!isNaN(this.value.replace(/,/g, "")))
                 this.value=this.value.replace(/,/g, "");
        });
    });
</script>

Fiddle Demo

or you can use regular expression using match() method

<script>
    $(function(){
        $("#textField").on('keyup', function(){
            if(this.value.match(/^\d*,\d*$/))
                 this.value=this.value.replace(/,/g, "");
        });
    });
</script>

Fiddle Demo

Upvotes: 2

Snehal S
Snehal S

Reputation: 875

try this,

$("#textField").on('keyup', function(){
    if(this.value.match(/[0-9]/g) != null) {
        this.value=this.value.replace(/,/g, "");
    }
});

Upvotes: 0

Miro
Miro

Reputation: 5337

if(this.value != null && this.value.match(/^\d{1,3}(,?\d{3})*?(.\d*)?$/)){
    this.value=this.value.replace(/,/g, "");
}

Upvotes: 0

Related Questions