Loading ...

Limit the maximum number of characters in textbox | CodeAsp.Net

Limit the maximum number of characters in textbox

 /5
0 (0votes)

In this blog I will explain how to limit the maximum number of characters in textbox. There are requirements when we want to fixed the length of characters in multiline textbox. Below is the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function() {

            $('#TestId').keyup(function(e) {

                var maxLength = 100;

                var textlength = this.value.length;

                if (textlength >= maxLength) {

                    $('#charStatus').html('You cannot write more then ' + maxLength + ' characters!');

                    this.value = this.value.substring(0, maxLength);

                    e.preventDefault();

                }

                else {

                    $('#charStatus').html('You have ' + (maxLength - textlength) + ' characters left.');

                }

            });

        });

    </script>

</head>
<body>
    <textarea id="TestId" cols="20" rows="8"></textarea><br />
    (Maximum characters: 100)<br />
    <span id="charStatus"></span>
</body>
</html>


Above i have used keup event of textbox and the function will continiously check the number of characters left for the user, and will show the the status accordingly in label.

 

Do let me know your feedback, comments.

 

Comments (no comments yet)

Top Posts