JavaScript determines the input box can only enter a number of methods

Source: Internet
Author: User

JavaScript only allows you to enter numbers in a number of ways, summarized below

1, only numbers and decimal points are allowed.

<onKeypress= "return (/[\d.) /.test (string.fromcharcode (event.keycode))) "  style=" ime-mode:disabled ">


2, judge the more detailed some, even 22. 2 That's not a number.

<script> <br>function check () {<br>    var i=document.getelementbyid ("tt"). Value;<br>    if (isNaN (i)) {<br>        alert ("illegal character! "); <br>        tt.value= "";<br>    } <br>} <br></script> <br><input type= "text" Name= "tt" id= "tt" onkeyup= "check ();" >

3, only integer input is Allowed. In fact, we can also make some restrictions according to the third article Extrapolate.

<script language=javascript>function  onlynum () {    if(!) ( Event.keycode==46) &&! (event.keycode==8) &&! (event.keycode==37) &&! (event.keycode==39))     if (! ((event.keycode>=48&&event.keycode<=57) | | (event.keycode>=96&&event.keycode<=105)))    Event.returnvalue=false;}
<onkeydown= "onlynum ();" style = "ime-mode:disabled" >

4, only a Number.

<onkeyup= "value=value.replace (/[^\d]/g, ')"  onbeforepaste= " Clipboarddata.setdata (' text ', clipboarddata.getdata (' text '). replace (/[^\d]/g, "))">

conclusion, In fact style= "ime-mode:disabled This sentence is more practical." Turn off the Ime. The best effect is 3, you can directly prohibit the input, 4 is the input after the replacement, so that the input has the opportunity to press enter, there will be unexpected results.

JavaScript determines the input box can only enter a number of methods

Related Article

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.