Dynamically expand height of input type “text” based on number of characters typed into field

UPDATED[2]:

As scrollHeight is always equal to height, we have to set height to ‘1’ before scrollHeight, then when we delete characters the <textarea> autofit:

$('textarea').on('keydown', function(e){
    if(e.which == 13) {e.preventDefault();}
}).on('input', function(){
    $(this).height(1);
    var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
    $(this).height(totalHeight);
});

Fiddle:

http://jsfiddle.net/mJMpw/551/

UPDATED:

As friends said, <input type="text"/> has no line breaks. My suggest using <textarea> is:

$('textarea').on({input: function(){
    var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
    $(this).css({'height':totalHeight});
}
});

Fiddle:

http://jsfiddle.net/mJMpw/548/

ORIGINAL ANSWER:

this is very ugly but you could do it like this:

$('input[type="text"]').on('keyup',function(){
    var text = $(this).val();
    var getWidth = $('<span class="getWidth" style="white-space:nowrap; width:auto;">' + text + '</span>').insertAfter(this);
    $(this).css({'width':getWidth.outerWidth()}).next('.getWidth').remove();
});

You have to specify the same fonts/padding property to .getWidth and you input:

input, .getWidth {
    font-family:arial;
    font-size:12px;
    font-weight:normal;
    letter-spacing:normal;
    padding:3px;
}

Fiddle:

http://jsfiddle.net/9SMRf/

Leave a Comment