<p class="text-input"> <input type="text" id="username" autoComplete='off' maxlength="30"> <span class="js_limit"> <em>0</em>/<span>30</span> </span> </p> <script src="jquery-1.7.2.min.js"></script> <script> $(function(){ $('#username').bind('input propertychange', function() { $('.js_limit em').html($(this).val().length); }); }) </script>
要是想監聽輸入字符的數量變化,同時超出的字符部分自動截取:
<p class="text-input">
<input type="text" id="username" autoComplete='off' maxlength="15" onkeyUp="textLimitCheck(this, 15);">
<span class="js_limit">
<em id="messageCount">0</em>/<span>15</span>
</span>
</p>
<script>
function textLimitCheck(thisArea, maxLength){ if (thisArea.value.length > maxLength){ alert(maxLength + ' 個字限制. \r超出的將自動去除.'); thisArea.value = thisArea.value.substring(0, 15); thisArea.focus(); } /*回寫span的值,當前填寫文字的數量*/ messageCount.innerText = thisArea.value.length; } </script>
試過了這個方法才知道,原來只用監聽字符數量就行,屬性maxlength就可以完成自動截取字符的功能