$(document).ready(function(){ // set the max chars $("textarea[@maxlength]").each(function(){ var max = this.getAttribute('maxlength'); var html_counter = "
0/" + max +" maximum
"; $(this).after(html_counter); //this.relatedElement = $('span')[0]; this.relatedElement = $('div.counter > span')[0]; }); // check the max chars $("textarea[@maxlength]").keyup(function(){ var maxLength = this.getAttribute('maxlength'); var currentLength = this.value.length; if(currentLength >= maxLength) { this.relatedElement.className = 'toomuch'; this.value = this.value.substring(0, maxLength); } else { this.relatedElement.className = ''; } this.relatedElement.firstChild.nodeValue = currentLength; }); });