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

I have code to remove a comma in a text box, but I need to remove the comma only when the entered value is a number , then the comma should be deleted, but not for the text

The 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="" />

Script here

+3
source share
4 answers

Use the check method whether it is a number or not isNaN()

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

Screenshot

or you can use regex using method match()

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

Screenshot

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

,

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

, jQuery, .

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

All Articles