Often there is a task to limit the possibility of entering letters in the input field. Many sources suggest doing this in the following way, hanging up a keyup event handler, with the following code:
return ((event.keyCode>47)&&(event.keyCode<58))
This method has a number of flaws, for example, the user will also not be able to enter the numbers numpad, the opera will not work the tab, up, left keys, etc.
How to do the right thing?
But there are also good ideas, which can be improved by finalizing the desired result.
function testKey(e) {
I decided to write a jQuery plugin based on this code. But in order not to reinvent the wheel, I decided to search for ready-made plugins, and found one
digitalbush.com/projects/masked-input-plugin . It's a really nice plug-in, but I needed it so that I could set the conditions for the field to be either integers or fractional numbers.
And so, what tasks I set myself:
- Set the type to "float", "int", or a regular expression.
- Set the delimiter for the type "float".
- Add the number of characters before and after the delimiter.
- The default value if the user has inserted a value through the context menu.
As mentioned earlier, when I pressed a key, I converted the code into a symbol, checked it through a regular expression. It remains to provide only the case if the user inserted the value through the context menu, for this I hung the handler on the blur event, where I performed the check through the regular expression we need.
However, when I began to check everything, I noticed if the user selected some part of the text in the Input with the mouse. He could insert an unresolved symbol, bypass this regular expression, in order to avoid it, I took the selected text (I had to struggle with cross-browser compatibility here) and checked it in accordance with the conditions.
Sources on
github and
demoUsed Books:
- habrahabr.ru/blogs/javascript/55922 .
- xpoint.ru/know-how/JavaScript/PoleznyieFunktsii?38#Fil 'trVvodaDlyaTekstovogoPolya