简体   繁体   English

在asp.net中计数错误的文本框字符

[英]counting characters of textbox erroring out in asp.net

I keep getting the error 0x800a1391 - JavaScript runtime error: 'txtMessage' is undefined what I am trying to do is to count the characters of a textbox 我一直收到错误0x800a1391-JavaScript运行时错误:'txtMessage'未定义,我想做的是计算文本框的字符

<script type="text/javascript">
    function textCounter(field, countfield, maxlimit)
    { 
        if (field.value.length > maxlimit)    
          field.value = field.value.substring(0, maxlimit);
        else
          countfield.value = maxlimit - field.value.length;
    }
</script>

Textbox that I have : 我拥有的文本框:

<asp:TextBox ID="txtMessage" TextMode="MultiLine"  Width="200px" Rows="3" runat="server"  onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);" />

and here I am counting: 我在这里数:

<input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters left

You are referring to a server side control. 您指的是服务器端控件。 In my situations, the ID specified on the server will not be the same as the ID on the client. 在我的情况下,服务器上指定的ID将与客户端上的ID不同。 You can correct that in a number of ways. 您可以通过多种方式进行更正。 The most straight forward is to change the ClientIDMode. 最直接的方法是更改​​ClientIDMode。

<asp:TextBox ID="txtMessage" ClientIdMode="static" TextMode="MultiLine"  Width="200px" Rows="3" runat="server"  onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);" />

Changing the mode to static will mean that it will use the ID that you specified. 将模式更改为静态将意味着它将使用您指定的ID。 Beware that you're now responsible for ensuring the ID is unique on the composited page (master page(s) + content page + user control(s)). 请注意,您现在负责确保ID在复合页面(母版页+内容页+用户控件)上是唯一的。

When dealing with JavaScript, always inspect the source using your browser. 处理JavaScript时,请始终使用浏览器检查源。 What you're looking at on the server may be different than what you get on the client. 在服务器上查看的内容可能与在客户端上查看的有所不同。

If you use script on client side, use javascript for access to controls. 如果您在客户端使用脚本,请使用javascript访问控件。 Try follows: 尝试如下:

<asp:TextBox ID="txtMessage" TextMode="MultiLine" runat="server"  Width="200px" Rows="3"  onkeyup="textCounter(this.value, 160);" onkeydown="textCounter(this.value, 160);" />
<input id='remLen' readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters left

And correct your script: 并更正您的脚本:

<script type="text/javascript">
function textCounter(value, maxlimit)
{ 
if (value.length > maxlimit)    
    value = value.substring(0, maxlimit);
else
    var countfield = document.getElementById('remLen');
    countfield.value = maxlimit - field.value.length;
}
</script>

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

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