本文實例介紹了jquery限定文本框只能輸入數字的詳細代碼,分享給大家供大家參考,具體內容如下
先來一段規定文本框只能夠輸入數字包括小數的jQuery代碼:
<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title>武林網</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">//文本框只能輸入數字(包括小數),并屏蔽輸入法和粘貼 jQuery.fn.number=function(){ this.bind("keypress",function(e){ var code=(e.keyCode?e.keyCode:e.which); //兼容火狐 IE //火狐下不能使用退格鍵 if(!$.browser.msie&&(e.keyCode==0x8)){return;} if(this.value.indexOf(".")==-1){return (code >= 48 && code<= 57)||(code==46);} else{return code >= 48 && code<= 57} }); this.bind("paste",function(){return false;}); this.bind("keyup",function(){ if(this.value.slice(0,1) == ".") { this.value = ""; } }); this.bind("blur",function(){ if(this.value.slice(-1) == ".") { this.value = this.value.slice(0,this.value.length-1); } }); }; $(function(){ $("#txt").number();}); </script></head><body><input type="text" id="txt" /></body></html>
2、jQuery如何規定文本框只能輸入整數:
有時候文本框的內容只能夠是數字,并且還只能夠是整數,例如年齡,你不能夠填寫20.8歲,下面就通過代碼實例介紹一下如何實現此功能,希望給需要的朋友帶來幫助,代碼如下:
<html> <head> <meta charset="gb2312"> <title>螞蟻部落</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">//文本框只能輸入數字(不包括小數),并屏蔽輸入法和粘貼 jQuery.fn.integer=function(){ this.bind("keypress",function(e){ var code=(e.keyCode?e.keyCode:e.which); //兼容火狐 IE //火狐下不能使用退格鍵 if(!$.browser.msie&&(e.keyCode==0x8)) { return ; } return code >= 48 && code<= 57; }); this.bind("paste",function(){ return false; }); this.bind("keyup",function(){ if(/(^0+)/.test(this.value)) { this.value = this.value.replace(/^0*/,''); } }); }; $(function(){ $("#txt").integer();}); </script></head><body><input type="text" id="txt" /></body></html>
以上代碼實現了我們的要求,文本框中只能夠輸入整數。
希望本文所述對大家學習jquery程序設計有所幫助。
新聞熱點
疑難解答