Introduction: In this article I am going to
share the JavaScript trick to automatically increase or resize the height
of text area or multiline text box according to the text content being written
in it.
In previous articles i explained how to Print page content placed inside DIV tag with print preview using JavaScript in Asp.net and Count and display remaining characters in the multiline textbox in asp.net and jQuery to resize multiline textbox on mouse over and mouse out and jQuery AJAX example to insert data into sql server database without postback and JavaScript to enable disable asp.net controls on textbox value change or typing text in TextBox
Implementation: Let’s create a
sample web page to demonstrate the concept.
HTML Source
<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>
Note: In this article I have demonstrated the concept using asp.net multiline textbox. But 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>
One more point to notice in the class (.clsTxt) that I have written 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. But 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.
Now over to you:
5 comments
Click here for commentsnyc
Replythanks for your feedback..stay connected and keep reading
Replyworks like a charm!!!!!!
ReplyThanks for your valuable comment..Stay connected and keep reading for more useful updates.
ReplyThank you, this was the simplest solution I managed to find on the www that actually works! Thank you!!
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..