How can I make textbox auto expandable through JavaScript?
            Asked
            
        
        
            Active
            
        
            Viewed 2,380 times
        
    -1
            
            
        - 
                    3you 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 Answers
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
 
    