We help IT Professionals succeed at work.

Javascript Resizing Textarea

purdyra1
purdyra1 asked
on
I used this code and overall it worked great BUT for some reason if I type in 18 characters it works fine, but if I type in 19 characters it grows by 2 lines instead of one, so by the time I enter 30 different lines, I have 30 extra lines at the bottom instead of just 1 or 2 extra lines at the bottom. I tried expanding the textbox width but that didn’t seem to help at all. Any small change I can make to the code or any idea of anything I can do, I really need this functionality and it’s great, thank you!


  <script type="text/javascript">
    function sz(t) {
                    a = t.value.split('\n');
                    b=1;
                    for (x=0;x < a.length; x++) {
                     if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
                     }
                    b+= a.length;
                     if (b > t.rows) t.rows = b;
                    }

I got the code from here.  
http://scvinodkumar.wordpress.com/2009/05/28/auto-grow-textarea-doing-it-the-easy-way-in-javascript/
Comment
Watch Question

Jens FiedererTest Developer/Validator

Commented:
It works fine for me in IE8 and Chrome (on a Windows 7 PC)

Maybe you could provide text of your whole page, and info about your environment?

Author

Commented:
Almost had it...
I had my code to go to IE7 compatibility.  So i took that out and it started working for 19 characters
but now when I get to 20 characters it adds an extra line!
I am on IE9, but I click on the compatibility, so with this clicked or unclicked it is now happening
On a windows 7 pc.
Test Developer/Validator
Commented:
How many cols is your TEXTAREA set to have?  19 or 20 by any chance?

Author

Commented:
it is set to zero.

Author

Commented:
ok... hold on, i just changed it to 32  (30 should be the max number i need), and it looks like when i hit 32 it added a 2nd line even though I could add more characters.  So this might be the fix, let me do some testing real quick, thx!
Jens FiedererTest Developer/Validator

Commented:
zero was definitely the wrong number to use!

Whether the cols EXACTLY fits the number of characters displayed depends somewhat on the type of font you are using - if it is not a fixed-width font, the calculation won't be exact (typing "." characters will give you very different results from typing "M" characters).

Author

Commented:
Ok, well that was it, I thought 0 meant unlimited.
Either way, it works alot better now ,thank you for yr time.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.