DIV CSS 佈局教程網

JS 限制 input 標籤只能輸入中文的方法
編輯:關於JavaScript     

這個方法很簡單,直接看示例即可。透過在 onkeyup 與 onbeforepaste 中用正規表達式過濾非中文字元,就能限制輸入框只能輸入中文。

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>只能輸入中文</title>
</head>
<body>
<input type="text" id="text"
 onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
 onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
</body>
</html> 

關鍵在於使用 /[^\u4E00-\u9FA5]/g 這個正規表達式,把不在常用中文字元範圍內的內容都替換掉;同時在貼上時也做同樣過濾,避免使用者用貼上的方式繞過限制。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved