[英]Get length of text area
我想在我的文本区域下方添加书面文本的长度。
为此,我定义了一个span
元素来编写我的字符。
但是,我目前收到以下错误:
未捕获的ReferenceError:未定义len
在下面找到我可行的示例:
$(".form-control.description").keyup(this.countCharacters.bind(this)) function countCharacters() { len = $(".form-control.rigDesc").val().length $(".remainChar").html("#" + len); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="form-group row" align="left"> <div class="col-7"> <textarea class="form-control rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea> <span class="remainChar"></span> </div> </div>
有什么建议如何捕获textarea字段的长度?
感谢您的答复!
您在textarea
中缺少类description
,因为您在keyup
事件中使用了$(".form-control.description")
,该事件正在寻找具有form-control
和description
类的元素,因此您需要在textarea
添加description
类。
$(".form-control.description").keyup(this.countCharacters.bind(this)) function countCharacters() { len = $(".form-control.rigDesc").val().length $(".remainChar").html("#" + len); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="form-group row" align="left"> <div class="col-7"> <textarea class="form-control description rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea> <span class="remainChar"></span> </div> </div>
为了提高准确性并防止意外错误,可以使用$("textarea.form-control.description")
来确保keyup
事件仅适用于具有form-control
和description
类的textarea
。
$("textarea.form-control.description").keyup(this.countCharacters.bind(this)) function countCharacters() { len = $(".form-control.rigDesc").val().length $(".remainChar").html("#" + len); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="form-group row" align="left"> <div class="col-7"> <textarea class="form-control description rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea> <span class="remainChar"></span> </div> </div>
您的代码将键盘绑定到错误的选择器。 我已经解决了这一问题,并确保len是局部变量而不是全局变量。 见下文:
$(".form-control").keyup(this.countCharacters.bind(this)) function countCharacters() { var len = $(".form-control.rigDesc").val().length; $(".remainChar").html("#" + len); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/> <div class="form-group row" align="left"> <div class="col-7"> <textarea class="form-control rigDesc" rows="4" id="comment" placeholder="Describe..."></textarea> <span class="remainChar"></span> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.