DIV CSS 佈局教程網

用 JavaScript 為輸入框加上字數限制
編輯:關於JavaScript     

在許多表單場景中,我們往往需要限制文字方塊可輸入的字元數量,一旦達到上限便停止輸入。以下用一段簡單的 JavaScript 來實現這個效果,並即時顯示當前已輸入的字數。

核心思路是:監聽輸入框的焦點與鍵盤事件,每次觸發時比對當前字元數與上限;若超出上限,就透過 substring 截斷多餘內容;否則更新計數顯示。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>輸入框字數限制</title>
<script type="text/javascript">
var textCounter = function(field, counter, maxlimit) {
    var charcnt = field.value.length;
    if (charcnt > maxlimit) {
        // 超過上限則截斷
        field.value = field.value.substring(0, maxlimit);
    } else {
        // 否則更新計數顯示
        document.getElementById(counter).innerHTML = charcnt;
    }
};
</script>
</head>
<body>
<p><span id="progressbar1">0</span>/12</p>
<form><input type="text" id="maxcharfield" size="34" /></form>
<script type="text/javascript">
document.getElementById("maxcharfield").onfocus =
document.getElementById("maxcharfield").onkeydown =
document.getElementById("maxcharfield").onkeyup = function() {
    textCounter(this, 'progressbar1', 12);
};
</script>
</body>
</html>

上述範例中,輸入框最多允許輸入 12 個字元,右上角會即時顯示「已輸入/上限」的比值。你可以依需求調整 maxlimit 參數與顯示區域的內容。需要注意的是,這種前端限制僅能提升使用者體驗,若對資料有嚴格要求,後端仍應再做一次長度校驗,以避免被繞過。

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