I'm not great with JavaScript. I've written a small jQuery function and I've now got it working, but I just wanted to check if the code looks good or if it can be improved.
I wanted a function so that I can easily add the function to any textarea and input so that it counts characters remaining and so I can just change the max count value so I don't have to keep writing out the whole thing for every input/textarea. I want it to show the max count on focus, add a css warn class to it when it is the last 10, and add a css max-reached class to it when the count has exceeded. Here it is:
var jq = jQuery.noConflict();
jQuery( document ).ready( function() {
jq.fn.cmCharactersLeft = function(options) {
// defaults
var defaults = {
maxLength: 300,
selector: '#testform .text-count'
};
var options = jq.extend(defaults, options);
jq(this).keyup(function() {
// character length variable
var character_length = jq(this).val().length;
// Characters left
if( character_length <= options.maxLength ){
jq( options.selector ).html( options.maxLength - character_length ).removeClass('max-reached count-warn');
}
// Characters left last 10
if ( character_length >= ( options.maxLength - 10 ) ){
jq( options.selector ).html( options.maxLength - character_length ).addClass('count-warn').removeClass('max-reached');
}
// Max characters reached
if ( character_length > options.maxLength ){
jq( options.selector ).html( options.maxLength - character_length ).addClass('max-reached').removeClass('count-warn');;
}
});
// show 'characters left' on focus too
jq(this).focus(function() {
// character length variable
var character_length = jq(this).val().length;
// Characters left
if( character_length < 1 ){
jq( options.selector ).html( options.maxLength );
}
});
}
});
Then I can use the above function for any textarea/input:
jQuery( document ).ready( function() {
jq('#form1 textarea').cmCharactersLeft({
maxLength: 50,
selector: '#form1 .text-count'
});
});
jQuery( document ).ready( function() {
jq('#form2 textarea').cmCharactersLeft({
maxLength: 200,
selector: '#form2 .text-count'
});
});
Example HTML:
<form id="form1">
<textarea></textarea>
<span class="text-count"></span>
<button type="submit">Submit</button>
</form>
Edit
Or, what would be a better way to write this?