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!
You can do something like this:
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 validkeyupvalue, you could use.toggleClass(), like this: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.