Reputation: 512
We have a very simple word counter that is working fine enough for our needs. We now need to make a modification to it though. Please see our JSfiddle at http://jsfiddle.net/MUSXU/1
(function($){
$.fn.textareaCounter = function(options) {
// setting the defaults
// $("textarea").textareaCounter({ limit: 100 });
var defaults = {
limit: 100
};
var options = $.extend(defaults, options);
// and the plugin begins
return this.each(function() {
var obj, text, wordcount, limited;
obj = $(this);
obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');
obj.keyup(function() {
text = obj.val().replace(/\s+/g, " ");;
if(text === "") {
wordcount = 0;
} else {
wordcount = $.trim(text).split(" ").length;
var URLs = text.match(/([^\s])+\.(com|net|org|biz|gov|edu|mobi|info|ca|us|mil)/g);
if(URLs != null && URLs.length > 0){
wordcount += (URLs.length*2);
}
}
if(wordcount > options.limit) {
obj.next().html('<span style="color: #DD0000;">-' + parseInt(wordcount - options.limit, 10) + ' words left</span>');
$("#submit").prop('disabled', true);
} else {
obj.next().html((options.limit - wordcount)+' words left');
$("#submit").prop('disabled', false);
}
});
});
};
})(jQuery);
$('textarea').textareaCounter({limit:15});
We have one issue though:
I am not that great at javascript and have just sort of hacked this together for our needs, and this is the final thing that I need working before we can deploy it.
I'd appreciate any help you can lend.
Upvotes: 1
Views: 192
Reputation: 570
You can use an array to hold your results to check for validation. see this...
http://jsfiddle.net/kmd97/Up9KS/
var res = [];
$("#submit").prop('disabled', false);
$.each(res, function (index, value) {
if (value) {
$("#submit").prop('disabled', true);
return false;
}
add this bit onload to mimic a keypress, probably the cleanest/simplest way to achieve the validation upfront.
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 40;
$("textarea").trigger(press);
Upvotes: 2