Friday, March 25, 2011

JavaScript to auto increase height of multiline text box

Here is the Java script code for auto resizing multiline text box. What it does is when user keeps typing in the text box and reach to the end line then text box height automatically increases.
<script type="text/javascript">
// this function takes text box as input parma which need to grow in height upon typing
    function AutoResizeMultilineTextBox(txtBox) {

        nCols = txtBox.cols; // find total columns set to the text box
        sVal = txtBox.value; // total characters
        nVal = sVal.length; // total lenth of the character
        nRowCnt = 1; // new row count variable reset to 1

        // this loop is written to find out total new row count to be added depending upon the character lenght
        //and new line found in the character
        for (i = 0; i < nVal; i++) {
            if (sVal.charAt(i).charCodeAt(0) == 13) {
                nRowCnt += 1;

        // check if new row count is less than the rown count covered by the character
        if (nRowCnt < (nVal / nCols)) { nRowCnt = 1 + (nVal / nCols); }
            txtBox.rows = nRowCnt+2;      


Example text box

<asp:TextBox ID="txtMsg" runat="server"  TextMode="MultiLine"  onkeyup="AutoResizeMultilineTextBox(this)" Rows="3" Columns="50" />

Above code will cover all scenarios
-          User Continuous typing
-          User keep hitting new line (Enter Button)
-          User hit back button

1 comment: