I have got this working ok, I just think that it can be improved and reduce the amount of code. If anybody could help that would be brilliant.
// Max Length Input
$('input[maxlength]').each(function() {
var maxCharLength = $(this).attr("maxlength");
if(maxCharLength < 0 || maxCharLength > 5000){
} else {
var charLength = $(this).val().length;
$(this).after("<span class='charCount clearBoth' id='charCount_"+$(this).attr("name").replace(".","_")+"'> " + charLength + " of " + maxCharLength + " characters used</span>");
$(this).keyup(function() {
var charLength = $(this).val().length;
$(this).next("span").html(charLength + ' of ' + maxCharLength + ' characters used');
if(charLength == maxCharLength ) {
$(this).next("span").html('<strong> Maximum of ' + maxCharLength + ' characters used.</strong>');
$(this).next("span").addClass("red");
} else { $(this).next("span").removeClass("red"); }
});
}
});
// Max Length textarea
$('textarea[maxlength]').each(function() {
var maxCharLength = $(this).attr("maxlength");
if(maxCharLength < 0 || maxCharLength > 5000){
} else {
var charLength = $(this).val().length;
$(this).after("<span class='charCount clearBoth'> " + charLength + " of " + maxCharLength + " characters used</span>");
$('textarea[maxlength]').keyup(function(){
var limit = parseInt($(this).attr('maxlength'));
var text = $(this).val();
var chars = text.length;
$(this).next("span").html(chars + ' of ' + limit + ' characters used');
if(chars > limit){
var new_text = text.substr(0, limit);
$(this).val(new_text);
$(this).next("span").html('<strong> Maximum of ' + limit + ' characters used.</strong>');
$(this).next("span").addClass("red");
} else { $(this).find("span").removeClass("red"); }
});
}
});