js規定文字框只能夠輸入字母和數字

admin發表於2017-02-11
有時候文字框只能夠限制輸入字母或者數字,下面就通過程式碼例項介紹一下如何實現此效果。

先看一段程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload=function(){
  var theText=document.getElementById("theText");
  theText.onkeyup=function(){
    this.value = this.value.replace(/[^a-zA-Z0-9]/g,"");
  }
}
</script>
</head>
<body>
<input type="text" id="theText" />
</body> 
</html>

以上程式碼只能夠說部分實現了我們的功能,通過鍵盤輸入的時候能夠實現此功能,但是如果通過滑鼠黏貼的話就不行了,下面將程式碼修改如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload=function(){
  var theText=document.getElementById("theText");
  theText.onkeyup=function(){
    this.value = this.value.replace(/[^a-zA-Z0-9]/g,"");
  }
  theText.onpaste=function(){
    var _this=this;
    setTimeout(function(){
      _this.value=_this.value.replace(/[^a-zA-Z0-9]/g, "");
    }, 0);
  }
}
</script>
</head>
<body>
<input type="text" id="theText" />
</body> 
</html>

以上程式碼可以完美實現我們的要求,無論是鍵盤輸入還是通過滑鼠複製黏貼都可以實現檢測功能。

相關文章