Reputation: 4693
I am working on a character count based on this post.
I would like to call the function on window load but seem to be having issues, otherwise everything works.
Can anyone lend a hand on getting the count on load please.
heres my fiddle
function countChar(val){
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
$('#stat span').text(0);
}else {
$('#stat span').text(500 - len);
}
}
$(function(){
var inputT = $('#descTextArea').val();
//countChar(inputT);//this is breaking the code
$('#descTextArea').keyup(function(){
countChar(this);
});
});
Upvotes: 0
Views: 6779
Reputation: 1677
Here is a quick and simple jQuery plugin I wrote. All you need to do is $("#element_id").jqCounter();
to give an input or textarea a character counter. It responds to paste, changes and everything else I could think of.
You must set the maxlength attribute for it to work, ie. <input maxlength=45 />
or <textarea maxlength=45></textarea>
<script>
(function($) {
$.fn.extend({
jqCounter : function(givenOptions) {
return this.each(function() {
var $this = $(this),
options = $.extend({
divider: "/" // The diveder character between the count and max
}, givenOptions);
// 0 chars or max count not set or already setup
if($this.attr("maxlength") <= 0 || $this.hasClass("jqCounter")) return;
// Add the counter text after the element
var span= $("<span style=\"font-size:10px;\">"+$this.val().length+options.divider+$this.attr("maxlength")+"</span>")
.insertAfter($this);
// Add a class
$this.addClass("jqCounter")
// React to keypresses, changes, paste, etc. and change the counter
.on('focus blur propertychange change input paste keydown keyup keypress', function(){
setTimeout(function(){
var maxChars = $this.attr("maxlength"),
txtLength = $this.val().length;
span.text( txtLength + options.divider + maxChars );
},
1);
});
});
}
});
})(jQuery);
$(document).ready(function()
{
// All text areas will have a content counter
$("textarea").jqCounter();
});
</script>
Upvotes: 1
Reputation: 207911
Try this instead
function countChar(val) {
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
$('#stat span').text(0);
} else {
$('#stat span').text(500 - len);
}
}
countChar($('#descTextArea').get(0));
$('#descTextArea').keyup(function() {
countChar(this);
});
In your code you were passing a string (the value) into your function which is trying to get the length of an element. Instead, by calling countChar($('#descTextArea').get(0));
you're just passing the element and allowing the function to find the length of the input as you intended.
Upvotes: 5
Reputation: 84
Use $(document).ready() to bind your event handlers when the window loads, like so:
$(document).ready(function() {
$('#descTextArea').keyup(function(){
countChar(this);
});
});
Upvotes: 0