任何人都可以简化我的代码,这项工作在我的页面上,但是当我在Google Developer工具控制台上查看时,我收到了此错误:
未捕获的TypeError:无法读取属性'长度'未定义的
代码如下:
<asp:TextBox ID="txtCounter" runat="server" Width="250px" TextMode="MultiLine"></asp:TextBox>
<SPAN id="chars"></SPAN>
<script>
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters"); }
else {
$('#chars').text( char2 + " Characters Remaining"); }
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').on('keyup keydown change',
function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit)
{ this.value = this.value.substring(0, limit); lengthtxt = limit; }
$('#chars').text((limit - lengthtxt) + " Characters Remaining")
});
};
</script>
答案 0 :(得分:0)
问题在于这一行:
$('textarea[id$=txtCounter]').on('keyup keydown change',
txtCounter在呈现给客户端时不是textarea控件的客户端ID。查看您的页面来源以查找客户端ID,或使用:
$('textarea[id$=<%= txtCounter.ClientID %>]').on('keyup keydown change',
这是我使用简单textarea的工作示例:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="./jquery-1.6.4.min.js" type="text/javascript"></script>
</head>
<textarea ID="txtCounter" Width="250px"></textarea>
<SPAN id="chars"></SPAN>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters");
}
else {
$('#chars').text( char2 + " Characters Remaining");
}
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').bind('keyup keydown change', function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit){
this.value = this.value.substring(0, limit);
lengthtxt = limit;
}
$('#chars').text((limit - lengthtxt) + " Characters Remaining");
});
}
</script>
</html>