Wednesday, July 4, 2012

Asp.Net jQuery set Textarea MaxLength


Unlike Textboxes, the <textarea> control doesn’t support the Max Length property; hence there is no direct way to impose maxlength for a textarea. However we can achieve this using jQuery.

 Using jQuery we can impose Max Length property to a textarea, by tracking the keypress and blur events of the textarea, the keypress event makes sure that the user does not type more than the allowed number of characters in the textarea, the blur event takes care of values which are copied into the textarea, on blur, we will truncate the text such that it doesn’t exceed the max allowed length.


Here is a full example
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>TextBox</title>
    <link type="text/css" href="Stylesheet.css" rel="Stylesheet" />
    <script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function() {
            $('#txtComment').keypress(function(evt) {
                var maxLength = 50;
                // Allow Delete & BackSpace keys
                if (evt.keyCode == 8 || evt.keyCode == 46) return true;
                // Allow Shift, Ctrl & Tab Key
                if (evt.keyCode == 16 || evt.keyCode == 17 || evt.keyCode == 9) return true;
                // Allow Arrow Keys
                if (evt.keyCode == 37 || evt.keyCode == 38 || evt.keyCode == 39 || evt.keyCode == 40) return true;
                // Check and restrict other Keys
                if ($(this).val().length > maxLength) {
                    return false;
                }
            });
            //
            $('#txtComment').blur(function() {
                var maxLength = 50;
                var text = $(this).val();
                if ($(this).val().length > maxLength) {
                    $(this).val(text.substr(0, maxLength));
                }
            });
        });
    </script>
</head>
<body>
    <form id="frmTextBox" runat="server">
<div id="pageControls">
<
asp:TextBox
ID
="txtComment"
runat="server"
TextMode="MultiLine"></asp:TextBox>
</
div>
    </form>
</body>
</html>


Search Flipkart Products:
Flipkart.com

No comments: