Set Max Length of Textbox Control using JQuery


Hello and Welcome,
I hope you enjoy the topics I have written in my previous posts. I appreciate; you like my post(s) and suggest me to do more elaboration on some topic(s).
Embed the following Script into your and section to enable J- Query on your page:
<script language="javascript" type="text/javascript" src="~/jquery-1.4.1.js"></script>
<script language="javascript" type="text/javascript" src="~/jquery-1.4.1.min.js"></script>


Here is our function to check max length of textbox control

<script type="text/javascript" language="javascript">

    $(document).ready(function () {

        $('#txtNumCharacter').keyup(function () {
            var CharLength = 20;                            // Number of character to set max
            chars = $('#txtNumCharacter').val().length; // Check how many characters entered into textbox
            $('#lblMsg').text(CharLength - chars);           // Set message to label
           
            if (chars > CharLength) {                       // Check whether character entered is greater than max set character
                $('#txtNumCharacter').val($('#txtNumCharacter').val().substring(0, CharLength));    // Remove the extra character
            }
        });
    });

</script> 

Here is our Textbox control and label to show our message:
<div>
    <asp:TextBox ID="txtNumCharacter" runat="server" TextMode="MultiLine" ></asp:TextBox> Characters Left : <asp:Label ID="lblMsg" ForeColor="Red" runat="server" >20</asp:Label>
    </div>

I need your feedback, suggestions to give your more valuable topics in future.
I hope you enjoy the topic.

Comments