动态字符计数器 - 标签不显示任何东西

时间:2017-06-27 20:54:10

标签: asp.net vb.net

我正在尝试创建一个动态字符计数器,用于显示文本框中的text.length。我正在尝试使用textchanged,但我认为我错过了一块,因为我的标签根本没有显示任何值。

ASP

<tr>
    <td style="vertical-align: middle">
        Note to Buyer:
    </td>
    <td>
        <asp:TextBox ID="txtNoteToBuyer" runat="server" Height="150px" MaxLength="425" TextMode="MultiLine" Width="400px"></asp:TextBox>
    </td>
    <td>    
        <asp:Label ID="lblCharacterCount" runat="server"></asp:Label>
    </td>
</tr>

VB

Protected Sub txtNoteToBuyer_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNoteToBuyer.TextChanged
    lblCharacterCount.Text = Len(txtNoteToBuyer.Text)
End Sub

1 个答案:

答案 0 :(得分:4)

赔率是你的事件没有被解雇。您需要将文本框的AutoPostBack属性设置为true。

<asp:TextBox ID="txtNoteToBuyer" runat="server" Height="150px" MaxLength="425" TextMode="MultiLine"
                        Width="400px" AutoPostBack="True"></asp:TextBox>

但是,这可能会导致响应缓慢。我建议使用JavaScript动态更新前端的计数而不需要回发。

为此,您需要在文本框中添加OnKeyUp="updateCount();"并添加脚本以更新页面的计数。以下是可以使用的脚本的一个示例:

<script type="text/javascript">
    function updateCount() {
        var countLabel = document.getElementById("<%=lblCharacterCount.ClientId%>");
        var textCount = document.getElementById("<%=txtNoteToBuyer.ClientId%>").value.length;
        countLabel.textContent = textCount + "";
    }
</script>