JavaScript restricted text boxes allow only numbers to be entered (once compared to current methods) _javascript tips

Source: Internet
Author: User
Most of the time you need to use the text box to limit the number of input, tried many methods, are not ideal, so decided to achieve one to play.

A method that has been used before

To control only numbers by onkeydown events:
Copy Code code as follows:

<input onkeydown= "Return event.keycode>=48&&event.keycode<=57| | event.keycode>=96&&event.keycode<=105 "/>

Masked input:http://digitalbush.com/projects/masked-input-plugin/via jquery plugin
Through the jquery plugin Meiomask:https://github.com/fabiomcosta/jquery-meiomask
OnKeyDown Event control is relatively troublesome, the above simplified version of many keys are not involved, the operation experience is rather bad.
The two plug-ins in jquery are flexible enough to meet most of the needs, but the restrictions on the length of the control input are inflexible (perhaps I didn't find a flexible way to use them?). )

Specific implementation Methods
Use some of the methods in the Maskedinput to extract the cursor position
Use the common method provided on StackOverflow to handle keystrokes on the keyboard: Http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input
Update: Refer to the keycode listed on Http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Then customize the two properties to set the number and decimal length of the input:
Data-numbers Control the length of digital input
Data-decimals Control the length of decimal input
The final full code implementation is as follows:
Copy Code code as follows:

function Validatedigitsonly (evt) {
var e = evt | | Window.event,
Key = E.keycode | | E.which;
if (
Backspace, Tab, Enter, ESC, Delete
Key = = 8 | | Key = = 9 | | Key = = 13 | | Key = = 27 | | Key = = 46 | |
Ctrl + A
(Key = = && Event.ctrlkey = = true) | |
Home, END, four arrow keys
Key >= && key <= 40) {
Return
}
if (E.shiftkey | | e.altkey | | e.ctrlkey) {
return false;
}
var el = E.target | | E.srcelement,
Maximum number length
NL = El.getattribute ("data-numbers") | | 15,
Max decimal length
DL = El.getattribute ("data-decimals") | | 2,
val = El.value,
"." Location
Dotindex = Val.indexof ("."),
RNG = Caret.call (EL),
The cursor is in the "." Left
Rleft = Rng.end <= Dotindex,
The cursor is in the "." Right
Rright = rng.begin > Dotindex;
if (
Digital
Key >= && key <= 57 | |
Number of numeric keypad input
Key >= && Key <= 105) {
if (Validatevalue (Dotindex, Val, Rleft, Rright, NL, DL))
Return
Select some text and do it again
val = val.substring (0, Rng.begin) + val.substring (rng.end);
Dotindex = Val.indexof (".");
if (Validatevalue (Dotindex, Val, Rleft, Rright, NL, DL))
Return
}
else if (
// ".", ","
(key = = 190/*| | key = = 188*/| |
On the numeric keypad, ".", ","
Key = = 110/*| | Key = = 109*/) &&
Allow decimal numbers to be entered
DL > 0) {
if (
"." was not entered and the number of decimal places after the entered position did not reach the upper limit
Dotindex = 1 && (rng.end = = Val.length | | val.substring (rng.end). Length <= dl) | |
"." was lost, and the selected text contains "."
Dotindex >-1 && rng.begin <= dotindex && dotindex < Rng.end)
Return
}
return false;
}
Validating the value entered
function Validatevalue (Dotindex, Val, Rleft, Rright, NL, DL) {
if (
"." has not been entered.
Dotindex = 1 && val.length < NL | |
The cursor position is in the "." Before
Rleft && val.substring (0, Dotindex). length < NL | |
The cursor is in the "." After and does not reach the decimal limit
Rright && val.substring (Dotindex + 1). length < DL)
return true;
return false;
}
Get cursor Position
function caret () {
var begin, end;
if (This.setselectionrange) {
begin = This.selectionstart;
end = This.selectionend;
else if (document.selection && document.selection.createRange) {
var range = Document.selection.createRange ();
Begin = 0-range.duplicate (). MoveStart (' character ',-100000);
End = begin + Range.text.length;
}
return {begin:begin, end:end};
}

How to use
The specific use of the following methods:
Copy Code code as follows:

<input type= "text" id= "T1"/>
<input type= "text" id= "T2" data-numbers= "5" data-decimals= "4"/>
<script>
document.getElementById ("T1"). onkeydown = validatedigitsonly;
document.getElementById ("T2"). onkeydown = validatedigitsonly;
</script>

Or simply write it in HTML:
Copy Code code as follows:

<input type= "text" id= "Lwme_text_3" onkeydown= "return Validatedigitsonly (event)"/>

If you introduce jquery, it's easier to use:
Copy Code code as follows:

<input type= "text" class= "Digitsonly"/>

Copy Code code as follows:

$ (". Digitsonly"). KeyDown (validatedigitsonly);

End
Although this method is not efficient in some places, and some keyboard keys have not yet been processed, do not rule out some cases may fail, but for the most part of the use is sufficient.
If you have any additional needs, please make your own changes, of course, there are better ways to share (*^__^*)
Over
ps:01.18 updated some of KeyCode's judgments and wrongly wrote the 110 as 109 ≡(▔﹏▔)≡
Also note: For the use of the right menu or the menu bar to paste in the need for additional processing
There is also an extreme situation where you select text in a Web page and drag it into a text box, or select text in a text box and drag it, which requires extra processing .
For the above two kinds of situations that require additional processing, the more convenient method is to add a validation, such as jquery.validate, such as form validation, otherwise it is difficult to deal with
PS: Under the WIN8, switch to Microsoft Pinyin may cause can not input, do not know other systems or other input method has this problem (*_*) (' ~ ~ ') = =

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.