DAK
DAK

Reputation: 1435

Textarea value count length jquery

I think i'm missing something or have a silly error. I'm trying to get the counter going for textarea & for some reason length of textarea value is always zero. Here is my same code for View:

@Html.TextAreaFor(x => x.Description, new { @maxlength = "4000", @onkeyup = "countChar(this)" })
@Html.Label("", " ", new { @id = "lblcount" })

my corresponding javascript is:

function countChar(val) {
    var max = 4000;
    var len = $("#txtDescription").val().length;
    if (len >= max) {
        $('#lblcount').text(' you have reached the limit');
        $('#lblcount').attr("class", "lblCountRed");
    } else {
        var ch = max - len;
        $('#lblcount').text(ch + ' characters left');
        $('#lblcount').attr("class", "lblCountGreen");
    }
};

The above code always sets label text to "4000 characters left" irrespective of number of characters I type inside textarea.

Upvotes: 0

Views: 9135

Answers (2)

PeterKA
PeterKA

Reputation: 24638

I would really NOT advice you to use inline JavaScript but here is what the function should be:

function countChar( elem ) {
    var max = 4000,
        len = elem.value.length,
        lbl = $('#lblcount');
    if(len >= max) {
        lbl.text(' you have reached the limit')
        .addClass("lblCountRed").removeClass('lblCountGreen');
    } else {
        var ch = max - len;
        lbl.text(ch + ' characters left')
        .addClass("lblCountGreen").removeClass('lblCountRed');
    }
}

If you wanted to accomplish this without inline JavaScript, you would:

  • remove @onkeyup = "countChar(this)"
  • then use the following code:

-

$(document).ready(function() {
    $("#Description").on('keyup', function() {
        var max = 4000,
            len = this.value.length,
            lbl = $('#lblcount');
        if(len >= max) {
            lbl.text(' you have reached the limit')
            .addClass("lblCountRed").removeClass('lblCountGreen');
        } else {
            var ch = max - len;
            lbl.text(ch + ' characters left')
            .addClass("lblCountGreen").removeClass('lblCountRed');
        }
    });
});

Upvotes: 3

MH2K9
MH2K9

Reputation: 12039

You used wrong selector. Your textarea ID is Description but you used txtDescription. You should use

var len = $("#Description").val().length;

instead of

var len = $("#txtDescription").val().length;

Upvotes: 0

Related Questions