user3807187 user3807187 - 3 months ago 22
C# Question

MVC words limit

I would like to count the words in the text area instead of each individual character.

Model Class

[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>

Answer

you can get the words count in the text by spliting the value by white spaces, like:

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