javascript判斷input框只能輸入數位方法

來源:互聯網
上載者:User

標籤:javascrip   斷行符號   arc   onkeyup   blog   amp   from   ace   eve   

javascript 只允許輸入數字有很多方法,總結如下

1,只允許輸入數字和小數點。

<input onKeypress="return (/[\d.]/.test(String.fromCharCode(event.keyCode)))" style="ime-mode:Disabled">

 

  
2,判斷的更詳細一些,甚至22..2這樣不算數字也判斷得出來

<script> <br>function check(){ <br>    var i=document.getElementById("tt").value;<br>    if ( isNaN(i) ) {<br>        alert("非法字元!"); <br>        tt.value="";<br>    } <br>} <br></script> <br><input type="text" name="tt" id="tt" onkeyup="check();">

3,只允許輸入整數。其實也完全可以根據第三條來舉一反三做一些限制。

<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;}</script> 
<input onkeydown="onlyNum();" style="ime-mode:Disabled">

4,只能是數字

<input onkeyup="value=value.replace(/[^\d]/g,‘‘)" onbeforepaste="clipboardData.setData(‘text‘,clipboardData.getData(‘text‘).replace(/[^\d]/g,‘‘))">

結語,其實style="ime-mode:Disabled這句是比較實用的。意為關閉IME。效果最好的是3,可以直接禁止輸入,4是輸入以後又替換,這樣輸入者有機會按斷行符號,會有意想不到的結果.

javascript判斷input框只能輸入數位方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.