Constraining Text Input to Specific Characters - J Query

Your shopping cart page has a quantity field, and you want to make sure users can only enter numbers into that field:


Find all elements with the only Numbers class, and listen for keydown and blur events.The keydown event handler will prevent users from typing non-numeric characters into the field. The blur event handler is a precautionary measure that cleans any data entered via Paste from the contextual menu or the browser’s Edit menu:


The keydown event is immediate and prevents users from typing non-numeric characters into the field. This could be replaced with a keyup event that shares the same handler as the blur event. However, users would see a non-numeral appear and then quickly disappear. I prefer just to prevent them from entering the character in the first place and avoid the flickering. The blur event protects against copying and pasting non-numeric characters into the text field. In the previous scenario, I’m assuming the user is either trying to test the limits of the JavaScript (something that I would do) or trying to copy and paste data from a spreadsheet. Neither situation requires immediate correction in my opinion.
If your situation is different and you expect users to be copying and pasting data from a spreadsheet, keep in mind that the regular expression I use does not account for a decimal point. So, a number like “1,000” would be cleaned to “1000” and the number “10.00” would also be cleaned to “1000” as well.
You’ll notice that the validKeyCodes variable is a string that starts and ends with commas.
What will happen when JavaScript is disabled? The user will be able to enter any characters they please. Always be sure to validate code on the server. Don’t rely on JavaScript to provide clean data.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics