我們可以根據onkeydown事件的event.keyCode即是ASCII Chart來判斷字符或數字等。相關鍵盤key對應的ASCII碼:
參考下面JavaScript代碼:
復制代碼 代碼如下:
<script type = "text/javascript">
function isNumeric(keyCode)
{
return ((keyCode >= 48 && keyCode <= 57) || keyCode == 8)
}
</script>
<script type = "text/javascript">
function isAlpha(keyCode)
{
return ((keyCode >= 65 && keyCode <= 90) || keyCode == 8)
}
</script>
<script type = "text/javascript">
function isAlphaOrNumeric(keyCode)
{
return ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || keyCode == 8)
}
</script>
例子,用戶只能輸入字符和數字,並使用onpaste事件,不能粘貼。
復制代碼 代碼如下:
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return isAlphaOrNumeric(event.keyCode);" onpaste = "return false;"></asp:TextBox>