為多行文字框加上字數上限,並即時提示還能打幾個字,是留言、評論表單的常見需求。以下以完整的 HTML 頁面示範:
<html>
<head>
<title>JS 限制 Textarea 字元個數</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script language="JavaScript">
function textCounter(field, countfield, maxlimit) {
// 三個參數:表單域、計數框、限制字數
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit); // 超過則截斷
else
countfield.value = maxlimit - field.value.length; // 顯示剩餘字數
}
</script>
</head>
<body>
<form name="myform" action="">
<textarea name="message" cols="28" rows="5"
onKeyDown="textCounter(message,remLen,6);"
onKeyUp="textCounter(message,remLen,6);"></textarea>
您還可以輸入:
<input name="remLen" type="text" value="6" size="5" readonly="readonly"> 個字符
</form>
</body>
</html>
函式邏輯:當輸入長度超過上限時,用 substring 把內容硬截在 maxlimit 之內;否則把「上限減目前長度」寫進計數框。同時掛上 onKeyDown 與 onKeyUp,讓按壓與放開按鍵時都能即時更新提示。計數框設為 readonly,避免使用者手動改動。