简体   繁体   English

将TextBox限制为500个字符

[英]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 ? 我试图限制我的文本框最多包含500个字符,例如,我想从用户那里收到一个问题,但最大长度为500,如何显示书写时还剩下多少个字符?

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. 没有内置元素或属性-您需要使用Javascript。

Assign an ID to your input and add a new element to hold the remaining character count 为您的输入分配一个ID并添加一个新元素以保留剩余的字符数

@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: 接下来,添加对jQuery的引用,并将以下Javascript添加到布局视图中:

<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: 结果应如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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