ASP.NET TextBox - jQuery Counter函数没有被触发

时间:2011-11-26 12:02:20

标签: c# jquery asp.net character counter

我有一个jquery函数,应该计算用户在ASP.NET文本框中键入的字符。此信息将显示在:

<span ID="remaining" class="label">160 characters remaining</span>
<span ID="messages" class="msgleft">1 message(s)</span>   

The jQUery function is shown below:

 <script type="text/javascript">
        $(document).ready(function () {
            var $remaining = $('#remaining'),
        $messages = $remaining.next();

            $('#messagetext').keyup(function () {
                var chars = this.value.length,
            messages = Math.ceil(chars / 160),
            remaining = messages * 160 - (chars % (messages * 160) || messages * 160);

                $remaining.text(remaining + ' characters remaining');
                $messages.text(messages + ' message(s)');
            });
        });
</script>

ASP.NET文本框的ID是messagetext但是没有触发jQuery函数/事件。当我使用HTML文本区域时,它工作正常。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

   //.net dynamic ClientID
   $('#<% = messagetext.ClientID %>').keyup(function () {
            var chars = this.value.length,
        messages = Math.ceil(chars / 160),
        remaining = messages * 160 - (chars % (messages * 160) || messages * 160);

            $remaining.text(remaining + ' characters remaining');
            $messages.text(messages + ' message(s)');
        });

   //jquery input id wildcard selector
   $("input:[id*=messagetext]").keyup(function () {
            var chars = this.value.length,
        messages = Math.ceil(chars / 160),
        remaining = messages * 160 - (chars % (messages * 160) || messages * 160);

            $remaining.text(remaining + ' characters remaining');
            $messages.text(messages + ' message(s)');
        });

答案 1 :(得分:0)

谢谢,工作。我不得不对此做一点改动:

$("[id$=messagetxt]").keyup(function () {
        var chars = this.value.length,
    messages = Math.ceil(chars / 160),
    remaining = messages * 160 - (chars % (messages * 160) || messages * 160);
        $('input[id=remaining]').val(remaining + ' characters remaining');
        $('input[id=messages]').val(messages + ' message(s)');
    });