The script below prevents a text field from accepting more than 200 words.
<script type='text/javascript'>
//adds word counter
$('.max200').each(function(){
$(this).parent().append('<p style="font-weight:bold">200 words remaining</p>');
});
// counts as you type
$('.max200').keydown(function(){
checkLength($(this));
});
//count after pasted
$('.max200').change(function(){
checkLength($(this));
});
function checkLength(element){
str=$(element).val();
str_array=str.split(/\W+/);
s=str_array.length;
l=200-s;
if(l<0){
//$(this).parent().find('.words_left').css('color','red');
shortened=str_array.slice(0,200);
shortened_str=shortened.join(' ');
$(element).val(shortened_str+ ' ');
l=0;
}
$(element).parent().find('.words_left').text(l +' words remaining');
}
</script>
To apply it the textarea needs to be in its own wrapper and have the class “max200” see below:
2 Comments
Annette
cool!
admin
Thank you Annette