aVC
aVC

Reputation: 2344

update charcount of multiple divs with single function

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>&nbsp;</a>');
        }
                else {
            $('#charNum').text(lim - len);
            $('#charNum').removeClass('exceeded');
        }
        }
};

HTML:
<div id='charNum' class='counter'>&nbsp;</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

Upvotes: 0

Views: 253

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

If you attach your event handler(s) with jQuery you can use this within 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:

<div id='charNum' class='counter'>&nbsp;</div>
<textarea id='description' name='description' data-maxChars="200" rows='10' cols='20'></textarea>
<div id='charNum2' class='counter'>&nbsp;</div>
<textarea id='otherfield' name='otherfield' data-maxChars="400" rows='10' cols='20'></textarea>

Then:

$(document).ready(function() {
    $("textarea[data-maxChars]").on("keyup blur", function(e) {
        var $this = $(this),
            $counter = $this.prev(),
            len = $this.val().length,
            maxChars = +$this.attr("data-maxChars");

        $counter.text(maxChars - len).toggleClass("exceeded", len > maxChars);
    });
});    

Demo: http://jsfiddle.net/nnnnnn/GTyW3/

Upvotes: 2

jcern
jcern

Reputation: 7848

If each textarea is going to have it's own div, you can just add an extra parameter to the countChar function which would be the name of the div. So you'd have something like:

function countChar(val,count,focus, charCountDiv)

then, instead of hardcoding it in the function, the jQuery would be:

$(charCountDiv) 

That should do what I think you are looking to do.

Upvotes: 0

Related Questions