Wednesday, 18 April 2012

Set max length for multiline textbox



Jquery Common Function:

setMaxLengh: function (id, len, msg) {

      if ($('#' + id).length == 0) return;

      if ($('#' + msg).length > 0) $('#' + msg).html(len + " Characters left");


      $('#' + id).keypress(function (e) {
          if ($(this).val().length >= len) {
              e.preventDefault();
          }
      });

      $('#' + id).keyup(function (e) {
          var total = parseInt($(this).val().length);

          if ($('#' + msg).length > 0) $("#" + msg).html('Characters entered <b>' + total + '</b> out of ' + len + '.');

          if (total >= len) $(this).val($(this).val().substring(0, len));
      });
  }

(or)

Javascript:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>set Max Length</title>
    <script type="text/javascript">
        //To display the number of characters left
        function CharactersCount() {
            var CharLength = '<%=txtMsg.MaxLength %>';
            var txtMsg = document.getElementById('txtMsg');
            var lblCount = document.getElementById('lblCount');          
            if (txtMsg.value.length > CharLength) {
                txtMsg.value = txtMsg.value.substring(0, CharLength);
            }
            lblCount.innerHTML = CharLength - txtMsg.value.length;          
        }
    </script>
    <style type="text/css">
.lblstyle
{
color:Red;
font-weight:bold
font-size11px;
font-familyverdana;
}
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
             
                <td>
                    <span style="font-family: Verdana; font-size: 12px">Left:</span>
                    <asp:Label ID="lblCount" runat="server" Text="100" CssClass="lblstyle"></asp:Label>
                </td>
            </tr>
          
            <tr>
                <td colspan="2">
                    <asp:TextBox ID="txtMsg" onkeyup="CharactersCount();" runat="server"
                        Style="overflow: hidden;" Height="80px" TextMode="MultiLine" Width="300px" MaxLength="100" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



No comments:

Post a Comment