Hello,

In a label, I am displaying the number of characters left in a textbox. Once the user goes into negative characters remaining, the label text turns red. If they try to submit the form, an alert message will popup letting them know they have exceeding the limit of characters. I am not sure how to store the state(text and color) of the label so that after the button click, when the page reloads, it will go back to what it was. Everytime it reloads, it goes back to "500 Characters Remaining" - which is the limit I am setting. I have also tried the C# code below - putting in the JS call in the Page_Load - but it is not working either. Any help would be great!

<script type="text/javascript">
    function CharCounter() {

        var textBox = document.getElementById('<%=lblCharCount.ClientID%>');
        var label = document.getElementById('<%=txtResDesc.ClientID%>');
        var charCount = 500 - textBox.value.length;
        label.innerHTML = charCount + " Characters Remaining.";
        if (charCount >= 0) {
            //within limit - display in black
           label.style.color = "black";
        }
        else {
            //negative chars - display in red
            label.style.color = "red";
        }
    }

    function charCountAlert() {
        var textBox = document.getElementById('<%= txtResDesc.ClientID%>');
        var charCount = textBox.value.length;
        if (charCount > 500) {
            alert("Error: Cannot submit Research Description with more than 500 characters.");
        }
    }
</script>


<asp:Label ID="lblCharCount" runat="server"/>
<asp:TextBox ID="txtResDesc" runat="server" Height="53px" TextMode="MultiLine" Width="90%" onkeyup="CharCounter()"></asp:TextBox>
<asp:Label ID="lblSubmitError" CssClass="redText" runat="server" />
<asp:Button ID="btnSubmitResearchDesc" runat="server" Text="Submit" Font-Bold="true" OnClientClick="return charCountAlert();"/>



//C# file
protected void Page_Load(object sender, EventArgs e)
{  
    if (!Page.ClientScript.IsStartupScriptRegistered("charCounter"))
    {
        Page.ClientScript.RegisterStartupScript((this.GetType()), "charCounter", "charCounter();", true);
    }
}

Recommended Answers

All 2 Replies

Consider disabling the button when the user exceeds the max characters.

I'm trying to include both JS and C# so that if they disable the JS it will not allow them to submit - and give them an error message. Disabling the button is a good idea - and I'm going to now include that - but I still need to figure out the backend and how to keep the text value of the label.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.