Everyone has seen this before – you are typing away in a TextArea (inside a form) and there’s a little message telling you how many characters you have left before the maximum.
It turns out that, using Jquery in MVC, that functionality is very easy to implement.
In this scenario, this will be a comments textbox. So, first of all – in your model – add a string property ‘Comments’ with the getter and settter.
Then, in your View, enter:
@Html.TextAreaFor(model => model.Comments,
new { rows = "11", cols = "90" })
The DIV will be where the message shows up. Now, inside a Document Ready function in your javascript Script Tag (using a 1000 character maximum), enter this:
$('#Comments').keyup(function () {
var max = 1000;
var len = $(this).val().length;
if (len >= max) {
$('#charNum').text(' you have reached the limit');
} else {
var char = max - len;
$('#charNum').text(char + ' characters left');
}
});
Then, each time you enter a character, it will be calculated and shown in the DIV.
It couldn’t get much easier than this!
All Things DotNet Discussed – Winforms/ASP.Net/SharePoint/WPF
Leave a reply
You must be logged in to post a comment.