OnlyPrograming
OnlyPrograming

Reputation: 125

limit TextBox to 500 characters

I am trying to limit my textbox to include max 500 character, for example i want to receive a question from the user but it the max length is 500 and how can i show the number of how many character left while writing ?

this is my code in the view, but i don't know its not working, i have tried various ways!

<li>
    @Html.LabelFor(m => m.TeacherQuestion, new { maxlength = 500 })
    @Html.TextBoxFor(m => m.TeacherQuestion  , new { maxlength = 500})
</li> 

Upvotes: 0

Views: 3334

Answers (1)

User 12345678
User 12345678

Reputation: 7804

There is no built-in element or attribute for this - you need to use Javascript.

Assign an ID to your input and add a new element to hold the remaining character count

@Html.TextBoxFor(m => 
    m.TeacherQuestion, new { id = "questionInput", maxlength = 500 })
<span id="charsLeft"></span>

Next add a reference to jQuery and add the following Javascript to your layout view:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(function () {
        $("#questionInput").keyup(function () {
            var charsLeft = $(this).attr("maxlength") - $(this).val().length;
            $("#charsLeft").text(charsLeft + " characters left");
        });
    });
</script>

(If you need to include the script in a normal view, please refer to this answer for guidance.)

The result should look something like this:

enter image description here

Upvotes: 1

Related Questions