Skip to content

Instantly share code, notes, and snippets.

@linxlad
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save linxlad/25634f29d391a6b1b088 to your computer and use it in GitHub Desktop.

Select an option

Save linxlad/25634f29d391a6b1b088 to your computer and use it in GitHub Desktop.
JavaSscript TextArea Character counter
App.questionnaire.TextAreaCharacterCounter = function () {
var textMax = 300,
textAreas = ['summary', 'directions'];
textAreas.forEach(function(textArea) {
var $textArea = $('#' + textArea);
App.questionnaire.updateTexAreaDescriptionWithCharacterCount($textArea, textMax);
$textArea.on('focus keyup' , function () {
App.questionnaire.updateTexAreaDescriptionWithCharacterCount($textArea, textMax);
});
});
};
App.questionnaire.updateTexAreaDescriptionWithCharacterCount = function(textArea, textMax) {
var $feedbackArea = $('.FormItem--' + textArea.attr('id') + ' .FormItem-description'),
textLength = App.questionnaire.getUTF8Length(textArea.val()),
textRemaining = textMax - textLength;
if (textRemaining < 0) {
textRemaining = '<span style="color: red;">' + textRemaining + '</span>';
}
$feedbackArea.html(textRemaining + ' characters remaining');
}
App.questionnaire.getUTF8Length = function(string) {
var utf8length = 0;
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utf8length++;
}
else if((c > 127) && (c < 2048)) {
utf8length = utf8length+2;
}
else {
utf8length = utf8length+3;
}
}
return utf8length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment