Click here to Skip to main content
15,922,533 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello guys,

I'm working on a project in which my textboxes will have to resize based on the user input, the width to be specific. I found this code but it's the height that resizes and i think that you have to make multiple functions for each textboxes since it uses document.getElementById. Is it possible to resize its width based on user input? Is there an alternative for this code to make it applicable to other textboxes? Thanks in advance.

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.length

        document.getElementById(txtBox.id).rows = therows;
        return false;
    }
}
Posted
Updated 3-May-12 9:26am
v2
Comments
[no name] 3-May-12 15:26pm    
Format code snippets when posting

hi guys,

I was able to solve the problem with a help of a friend. Here it goes.

XML
1. Control declaration:

<asp:TextBox ID="txtMsg" runat="server"  TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="2" />


2. JavaScript function:

JavaScript
 function AutoExpand(txtbox) 
{
txtbox.style.height = "1px";
txtbox.style.height = (25 + txtbox.scrollHeight) + "px";
}
 
Share this answer
 
v2
The rows property of course changes the height of the element. If you want to change the width then use this http://api.jquery.com/width/[^] or this http://api.jquery.com/css/[^]

You should learn to use JQuery.
 
Share this answer
 
v2
Rows used to increase height of TextBox.

Could you use please try with 'Cols' atttribute/ property
 
Share this answer
 
Comments
Michael Sernal 4-May-12 9:51am    
hi,
i tried to change the below code:
var newtext = thetext.split("\n");
document.getElementById(txtBox.id).rows = therows;

to this:
var newtext = thetext.split(" ");
and this:
document.getElementById(txtBox.id).columns = therows;

but nothing happens to the width or column when i press enter, and also i would like to change the event to spacebar but couldn't the keycode for spacebar, any ideas? thanks.
Michael Sernal 4-May-12 9:58am    
got the keycode for spacebar 32, but couldn't find a way to make it work, would you mind showing me in code? thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900