views:

274

answers:

2

Hi I have a function to increase the No. of rows of a textarea when the user types on it, so it works fine. But when the form brings the text into the textarea as the user is not typing in, it does not increase the number of rows, but it shows only the number of rows defined at the beginning (rows="1"), as I need it to be the smallest number of rows.

I don't know what Javascript (no JQuery) function to apply to the textarea so it would expand the No. of rows, when the user types, and when the form bring up a multi line text to the textarea, so it will always uses the minimum amount of rows.

Any help would be appreciated.

Please fell free to change function I have completely.

eg.

<script type="text/javascript">
function changeTextAreaLength(e){
    var txtLength = e.value.length;
    var numRows = 0 ;
    var arrNewLines = e.value.split("\n");

    for(var i=0; i<=arrNewLines.length-1; i++){
        numRows++;
        if(arrNewLines[i].length > e.cols-5) {
            numRows += Math.floor(arrNewLines[i].length/e.cols)
        }   
    } 
        if(numRows < 1) {
            e.cols = (txtLength % e.cols) + 1 >= e.cols ? ((txtLength % e.cols) + 1) : e.cols ;
        }else{
            e.cols = e.cols ;    
            e.rows = numRows;
        }
}
</script>


<textarea id="textarea1" rows="1" onkeyup="javascript:changeTextAreaLength(this);" />
+1  A: 

First, change "fucntion" to "function".

Second, remove the "javascript:" from your onkeyup attribute.

Third, you are calling changeTextAreaLength() but your function is named expandtextarea().

Fourth, your function says expandtextarea(obj) but you refer to e, not obj, within the function.

<textarea id="textarea1" rows="1" onkeyup="expandtextarea(this);" />

ithcy
+4  A: 

Yeah, keyup isn't nearly enough to catch every way an input's content can change. There's also right-click cut/copy/paste, undo/redo, drag/drop and spelling corrections to consider even before you come to scripted changes.

You don't have any hope of catching all of those cases, so if you want a general realtime reaction to changes you have no alternative but to poll it (eg. using an interval). You can add keyup as well if you want to catch the common case of just typing with a quicker delay than the poller.

An alternative to character counting you might also consider would be checking the scrollHeight to see whether the textarea has started to scroll. eg. something like:

<textarea id="q" rows="4" cols="80">hello</textarea>
<script type="text/javascript">
    function stretchy(element) {
        var value= element.value;
        function update() {
            var h= element.scrollHeight;
            if (h>element.offsetHeight || h<element.offsetHeight-48)
                element.style.height= (h+24)+'px';
        }
        element.onkeyup= update;
        setInterval(update, 1000);
        update();
    }

    stretchy(document.getElementById('q'));
</script>
bobince
+1, nice answer
ithcy