Question

I'm currently using jQuery to restrict a text box to number only input as follows:

    $('input.numbersOnly').keyup(function () { 
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });

I'd like to let the user know that what they are typing is being rejected by changing the background color of the field. I know that I can change the background of a field using something like this:

     $('input.numbersOnly').addClass('alertClass');

My question is, how do I combine the two code examples above so that the color of the field changes as the character is getting replaced? My goal is to alert the user that something is wrong with their input as they type it in the field.

Thanks!

Was it helpful?

Solution

You can do something like this:

$('input.numbersOnly').keyup(function () { 
    var newValue = this.value.replace(/[^0-9\.]/g,'');
    if(this.value !== newValue) $(this).addClass('alertClass');
    this.value = newValue;
});

This grabs the new value, determines if you're actually replacing something, and if so adds the alertClass. If you wanted to also remove the class on a valid keyup value, you could use .toggleClass(), like this:

$('input.numbersOnly').keyup(function () { 
    var newValue = this.value.replace(/[^0-9\.]/g,'');
    $(this).toggleClass('alertClass', this.value !== newValue);
    this.value = newValue;
});

This would toggle the class on with an invalid keyup, causing a value adjustment, and togle it off if the last keypress was a valid one, resulting in no adjustment.

OTHER TIPS

Like this:

$('input.numbersOnly').keyup(function () { 
    var oldVal = this.value;
    this.value = this.value.replace(/[^0-9\.]/g,'');
    if (oldVal !== this.value)
        $(this).addClass('alertClass')
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top