-1

The below code to validate TextBox is working fine onkeypress but when I use backspace to reduce the text length this code is unable to return back to the RED color. How to change color back to red on using backspace to reduce string length.

<script type="text/javascript">

    function limitlength(obj, length) {
        var maxlength = length
        if (obj.value.length > maxlength) {
            document.getElementById("TextBox1").style.backgroundColor = "green";
        }
        else
        {
            document.getElementById("TextBox1").style.backgroundColor = "red";
        }

    }

</script>

Enter text (max length is 5 characters):
<form id="form1" runat="server">
<br />
<br />
<asp:TextBox ID="TextBox1" onkeypress="return limitlength(this, 5)" runat="server"></asp:TextBox>
<br />
<br />
</form>

2 Answers 2

1

try using onkeydown or onkeyup event.

Sign up to request clarification or add additional context in comments.

Comments

0

Either use onchange or onkeyup. I think it's better if you use onkeyup

Comments

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.