Why isnt this jquery working? Jquery Character Count
HTML
<input type='text' id='addComment' name='addComment' />
<div class='counter' style='margin:0; padding:0;'> </div>
JS:
<script type="text/javascript">
$('#addComment').each(function(){
// get current number of characters
var len开发者_JS百科gth = $(this).val().length;
// get current number of words
//var length = $(this).val().split(/\b[\s,\.-:;]*/).length;
// update characters
$(this).parent().find('.counter').html( 254 - length + ' characters left');
// bind on key up event
$(this).keyup(function(){
// get new length of characters
var new_length = $(this).val().length;
// get new length of words
//var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;
// update
$(this).parent().find('.counter').html( 254 - new_length + ' characters left');
});
});
</script>
It works for me.
You probably want to know how to limit it once it exceeds the limitation.
Just do this...
$(this).val(function(index, oldValue) { return oldValue.substring(0, 254); })
jsFiddle.
精彩评论