-1

The below code is works using document.write. How to display the value exceeded in Label1 and also how to change the background color of TextBox to red (Using JavaScripts) if value exceeded.

<script type="text/javascript">

    function limitlength(obj, length) {
        var maxlength = length
        if (obj.value.length > maxlength)
         document.write("Exceeded")        }

</script>

Enter text (max length is 5 characters):
<form id="form1" runat="server">
<asp:textbox ID="TextBox1" onkeypress="return limitlength(this, 5)" runat="server"></asp:textbox>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
3
  • 1
    There is no question being asked here. Commented Aug 30, 2011 at 17:03
  • 2
    this is clearly homework Commented Aug 30, 2011 at 17:04
  • @James - Have you read it? first read it completely. Commented Aug 30, 2011 at 17:13

2 Answers 2

2

You need to add an ID to the textbox.

function limitlength(obj, length) {
    var maxlength = length
    if (obj.value.length > maxlength) {
        document.getElementById("Label1").innerHTML = "Exceeded";
        document.getElementById("TextboxID").style.backgroundColor = "red"; 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works but backgrondcolor changes to red right from first keypress
1

First, I would pretty up the javascript:

function limitlength(obj, length) {
    var maxlength = length;
    if (obj.value.length > maxlength)
     document.write("Exceeded");
}

Second, since you are using .NET you will need to use the ClientID property on your textbox control. And please assign it an ID. For example, txtBox.

Third, you can change the background color like this:

function limitlength(obj, length) {
    var maxlength = length;
    if (obj.value.length > maxlength) {
     document.getElementById("<%=Label1.ClientID%>").innerHTML = "Exceeded"; 
     document.getElementById("<%=txtBox.ClientID %>").style.backgroundColor = "red";
    }
}

1 Comment

I am unable to understand the code. How to change background color of TextBox1 to red?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.