本文實(shí)例介紹了jquery限定文本框只能輸入數(shù)字的詳細(xì)代碼,分享給大家供大家參考,具體內(nèi)容如下
先來一段規(guī)定文本框只能夠輸入數(shù)字包括小數(shù)的jQuery代碼:
<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title>武林網(wǎng)</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">//文本框只能輸入數(shù)字(包括小數(shù)),并屏蔽輸入法和粘貼 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如何規(guī)定文本框只能輸入整數(shù):
有時(shí)候文本框的內(nèi)容只能夠是數(shù)字,并且還只能夠是整數(shù),例如年齡,你不能夠填寫20.8歲,下面就通過代碼實(shí)例介紹一下如何實(shí)現(xiàn)此功能,希望給需要的朋友帶來幫助,代碼如下:
<html> <head> <meta charset="gb2312"> <title>螞蟻部落</title> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">//文本框只能輸入數(shù)字(不包括小數(shù)),并屏蔽輸入法和粘貼 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>
以上代碼實(shí)現(xiàn)了我們的要求,文本框中只能夠輸入整數(shù)。
希望本文所述對(duì)大家學(xué)習(xí)jquery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注