简体   繁体   English

Textarea值计数长度jQuery

[英]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. 我正在尝试将计数器用于textarea,由于某种原因,textarea值的长度始终为零。 Here is my same code for View: 这是我与View相同的代码:

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

my corresponding javascript is: 我对应的javascript是:

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. 上面的代码始终将标签文本设置为“剩余4000个字符”,而不管我在textarea中键入的字符数如何。

I would really NOT advice you to use inline JavaScript but here is what the function should be: 我真的建议您使用内联JavaScript,但这是应该的功能:

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: 如果要在没有内联JavaScript的情况下完成此操作,则可以:

  • remove @onkeyup = "countChar(this)" 删除@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');
        }
    });
});

You used wrong selector. 您使用了错误的选择器。 Your textarea ID is Description but you used txtDescription . 您的textarea ID为Description但您使用了txtDescription You should use 你应该用

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM