简体   繁体   中英

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> 

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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