sam sam - 1 month ago 13
HTML Question

add new row to textarea input while editing

I wonder how to add new row/line to textarea while editing that is when the number of letters exceeds number of cols of the textarea add new line automatically.

Answer

Some basic code to achieve this, tested in this jsfiddle (http://jsfiddle.net/NZbZn/). It will need work, obviously, but shows the basic concept.

jQuery(document).ready(function(){

    //after typing occurs
    jQuery('textarea#expander').keyup(function(){

        //figure out how many chars
        var length = jQuery(this).val().length;

        //if more than 10
        if(length > 10){

            //if the modulus 10 of the length is zero, there are a multiple of 10 chars, so we need to extend by a row
            //(NOTE the obvious problem - this will expand while deleting chars too!)
            if((length % 10) == 0){

                //figure out the number of rows, increment by one, and reset rows attrib
                var rows = jQuery(this).attr('rows');
                rows++;

                jQuery(this).attr('rows', rows);    
            }  
        }   
    });    
});

Again though, consider the UI implications first.