<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就可以完成自动截取字符的功能

05-11 18:09