規定文字框只能夠輸入數字包括小數的jQuery程式碼

antzone發表於2017-03-02

文字框有時候規定只能夠輸入整數,這裡就不多介紹了,具體可以參閱jQuery如何規定文字框只能輸入整數一章節,不過有時候也可以輸入小數,下面就通過程式碼例項介紹一下如何實現此功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<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>

以上程式碼實現了我們的要求,文字框中只能夠輸入整數。

相關文章