-1

How can I make textbox auto expandable through JavaScript?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Piyush
  • 5,145
  • 16
  • 49
  • 71
  • 3
    you have asked this question/very related question four times in the last 24hrs - here, http://stackoverflow.com/questions/2949051/textbox-auto-resize-in-jquery, http://stackoverflow.com/questions/2949249/textbox-auto-expandable, and http://stackoverflow.com/questions/2948230/auto-expand-textarea. One with and one without jQuery would of been more ideal – Dr. Frankenstein Jun 02 '10 at 13:18

3 Answers3

0

I suggest using a javascript library such as jQuery and then using a plugin such as this one:

http://james.padolsey.com/javascript/jquery-plugin-autoresize/

Kerry Jones
  • 21,806
  • 12
  • 62
  • 89
  • but in my case it is suggestion that i have to use the javascript only then how can i do it pls – Piyush Jun 02 '10 at 09:16
0

You could compare the count of your value with the rows * cols. I dont really know how many letters there are in a col in html but if you tested that you could do something like:

var colCount =  document.yourForm.yourTextArea.cols;
var rowCount =  document.yourForm.yourTextArea.rows;
if((colCount * numberOfLettersInACol) * rowCount) <= document.yourForm.yourTextArea.value.length){
    document.yourForm.yourTextArea.rows = rowCount + 1;
}
Matschie
  • 1,237
  • 10
  • 9
0

Give the textarea an ID of "textarea-expand" and try this:
Note: This does not 'reshrink' when you delete the text - it only expands
Edit: (now works without jquery)
Edit: online demo at http://bit.ly/aOik0B

<script type="text/javascript">

// ---------- FitToContent ----------

var maxHeight;

function fitToContent(idSelector) {

 var text = idSelector && idSelector.style ? idSelector : document.getElementById(idSelector);
    if ( !text ) {
      return;
 }

 function adjustHeight(idSelector, maxHeight) {
    var adjustedHeight = text.clientHeight;
    if ( !maxHeight || maxHeight > adjustedHeight ) {
        adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
        if ( maxHeight ) {
           adjustedHeight = Math.min(maxHeight, adjustedHeight);
        }
        if ( adjustedHeight > text.clientHeight ) {
           text.style.height = adjustedHeight + "px";
        }
    }
  }

  adjustHeight(text, document.documentElement.clientHeight);

}

window.onload=function(){
    function init(){
        fitToContent("textarea-expand");
    }
    init();
    document.getElementById("textarea-expand").onkeypress = init
};

</script>
Dr. Frankenstein
  • 4,634
  • 7
  • 33
  • 48