MVC单词限制

时间:2016-08-30 03:28:02

标签: javascript c# asp.net-mvc

我想计算文本区域中的单词而不是每个单独的字符。

模型类

  [RegularExpression(@"[^<>]*", ErrorMessage = "Invalid entry"), StringLength(200)]
        public string Day1Journal { get; set; }

HTML

@Html.TextAreaFor(m => m.StudentJournaldtls.Day1Journal, IsReadOnly == true || IsSubmitted == true ? (object)new { col = 2, @class = "CharacterLimit required", @maxlength = 200, @readonly = "readonly" } : new { col = 2, @class = "CharacterLimit required", @maxlength = 200 })
                            <small>No of characters left:<span class="charsLeft"></span></small>

的Javascript

<script type="text/javascript">
    $(function () {

$(".CharacterLimit").each(function (i, t) {
    var charsLeft = $(this).attr("maxlength") - $(this).val().split(' ').length
    $(this).parent().find(".charsLeft").text(charsLeft);
});

$(".CharacterLimit").keyup(function (e) {
    var charsLeft = $(this).attr("maxlength") - $(this).val().split(' ').length
    $(this).parent().find(".charsLeft").text(charsLeft);
});

</script>

1 个答案:

答案 0 :(得分:3)

您可以通过将值除以空格来获取文本中的单词,例如:

$("textbox").val().split(' ').length