Expandable or Auto-Resize TextBox Height
Recently, I was asked to prepare a Facebook like expandable textbox in a ASP.NET web application, where user can input text and the textbox can be re-sized (more specifically the height) dynamically.
I searched for a while and found quite a lot of solutions that use jQuery (example). However, I was looking for something more intrinsic and simple, and finally I found another script on a forum that just use few lines of JavaScript codes:
1. Control declaration:
<asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this, event)" Rows="2" />
2. JavaScript function:
function AutoExpand(txtBox, event)
{
if (event.keyCode == "13" || event.keyCode == "8") {
var therows = 0
var thetext = document.getElementById(txtBox.id).value;
var newtext = thetext.split("\n");
therows += newtext.lengthdocument.getElementById(txtBox.id).rows = therows;
return false;
}
}
That's it. Just put the script above in a script file and then re-use it for any buttons in the whole application.