clear a text input if there are non numeric values with jquery

good morning all, I would like to make a simple widget, that checks a text input on focus and if there are some non numeric characters, it clear the value (ie if there is some kind of text) actually i' working on this:

$("#textinpId").focus(function() {

    if( $(this).val() == "Default Text" ) {
        $(this).val("");
    }

});

but i would like to generalize it to not only to "default text" but any non numeric digit (phone numbers), and next but not less important, i would like to trigger the event both on focus and on unfocus, but this part i'm sure i can handle myself :D

is that possible?

Upvotes: 0

Views: 3074

Answers (4)

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Try this

jQuery('#phone').keyup(function(){
    if(!isNumber($(this).val()))
    {
       $(this).val('');
    }
    });

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

FIDDLE

UPDATE

Checking on focus too

FIDDLE

For allowing only DECIMAL numbers

FIDDLE

Upvotes: 1

patel.milanb
patel.milanb

Reputation: 5992

you can do this using pure javascript and regex

var result  = /^[0-9]+$/.test(input);
if(!result)
  $('#textBoxID).val('');

This returns true if the input is numeric or false if not.

Upvotes: 0

Collin Henderson
Collin Henderson

Reputation: 1154

$('#textinpId').focus(function(){
    var regex = /^\d+$/;
    if(!regex.test($(this).val())) {
        $(this).val('');
    }
}); 

Upvotes: 4

Nitin Varpe
Nitin Varpe

Reputation: 10694

Use Following function on onkeypress event for accepting only decimal values

<input type="text" onkeypress=" return isNumberKey(event)"/>

  function isNumberKey(evt) {
                var charCode = (evt.which) ? evt.which : event.keyCode
                if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
                    return false;

                return true;
            }

For only integer you can use

<input type="text" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"/>

Upvotes: 2

Related Questions