Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Thursday 26 February 2015

Introduction:

 In this article I will explain the JavaScript code to automatically increase or resize the height of text box or multiline text box according to the text content.


In case of entering large data in textbox, it is required to increase the size of the textbox according to the data. It can be done by using jQuery or javacript code. In this expamle I am using folloeing javacript code:
Javascript Code:
    <script>
        function resizeTextBox(txt) {
            txt.style.height = "1px";
            txt.style.height = (1 + txt.scrollHeight) + "px";
        }
    </script>

Full Page Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .clsTxt {
            width: 200px;
            min-height: 25px;
            max-height: 200px;
            resize: none;
        }
    </style>
    <script>
        function resizeTextBox(txt) {
            txt.style.height = "1px";
            txt.style.height = (1 + txt.scrollHeight) + "px";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Description: </td>
                    <td>                       
                        <asp:TextBox ID="txtDescription" CssClass="clsTxt" runat="server"onkeyup="resizeTextBox(this)" TextMode="MultiLine"></asp:TextBox>
                        <%--<textarea class="clsTxt" onkeyup="resizeTextBox(this)"></textarea>--%>
                    </td>
                </tr> 
            </table> 
        </div>
    </form>
</body>

</html>

In this article I have demonstrated the concept using asp.net multiline textbox.
If you want to implement it on HTML textarea then use 
<textarea class="clsTxt" onkeyup="resizeTextBox(this)"></textarea>
Instead of
<asp:TextBox ID="txtDescription" CssClass="clsTxt" runat="server" onkeyup="resizeTextBox(this)"TextMode="MultiLine"></asp:TextBox> 

Note:  I have fix the maximum height 200px. i.e. max-height: 200px; so when textbox height reaches 200px then its height will not increase further and vertical scrollbar will appear as shown in demo image above.

If you don’t want this then remove max-height: 200px; from the class (.clsTxt) and it will infinitely increase its height based on content.
Categories: , ,

0 comments:

Post a Comment