Thursday, 30 January 2014

Maximum Length Control of multiline Textbox in asp.net using jquery




 <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>