I have a textarea where I am limiting the amount of words that can be typed in. It works fine and stops the user from entering in additional text but it has a problem. If the user copy/pastes into the textarea, they can break the rule. I'm not sure how to go about fixing that.
I know it probably has to do with the onpaste
event but how would I implement it into this code:
jQuery(document).ready(function($) {
var max = 100;
$('#text<? echo $rowcat2['cfid'];?>').keypress(function(e) {
if (e.which < 0x20) {
return;
}
var value<? echo $rowcat2['cfid'];?> = $('#text<? echo $rowcat2['cfid'];?>').val();
var regex = /\s+/gi;
var wordCount<? echo $rowcat2['cfid'];?> = value<? echo $rowcat2['cfid'];?>.trim().replace(regex, ' ').split(' ').length;
if (wordCount<? echo $rowcat2['cfid'];?> == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount<? echo $rowcat2['cfid'];?> > max) {
// This doesn't work.
this.value = this.value.substring(0, max);
}
});
});