I am trying to use a code snippet I found online to implement charcount. It works for one single text area. I have multiple text areas with different count limits. Here is the code that works for one single form.
Javascript:
function countChar(val,count,focus){
var len = val.value.length;
var lim=count;
var focussed=focus;
if (len >= lim) {
$('#charNum').text(lim - len);
$('#charNum').addClass('exceeded');
/* val.value = val.value.substring(0, lim);*/
}else {
if(focussed===0){
$('#charNum').html('<a> </a>');
}
else {
$('#charNum').text(lim - len);
$('#charNum').removeClass('exceeded');
}
}
};
HTML:
<div id='charNum' class='counter'> </div>
<textarea id='description' name='description' onkeyup=\"countChar(this,200,1)\" onblur=\"countChar(this,200,0)\" rows='10' cols='20'></textarea>
If I have two text areas, how can I modify this code to work ? I know how to get the id of the div in the script, But I dont know how to correctly update the counter div, say #charNum1, and #charNum2. Appreciate some hints. Thanks
EDIT:
I was thinking, I can name the counter div as “Charnum+divName” if that helps
If you attach your event handler(s) with jQuery you can use
thiswithin the handler to refer to whichever element the event was triggered on, thus avoiding having to hardcode element ids inside your function.I’d suggest adding an attribute with the max chars allowed and removing the inline event handlers:
Then:
Demo: http://jsfiddle.net/nnnnnn/GTyW3/