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

auto expand input width based on text length
textarea auto height based on content
auto resize input text
how to increase height of textbox in html
expand textarea dynamically
textarea resize
auto resize textarea to fit content
textarea increase height

Similar to the below JSFiddle (which I bookmarked and do not know from where the original question emerged):

http://jsfiddle.net/mJMpw/6/

<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 10 }' />

input {
    width: 200px;
    min-width: 200px;
    max-width: 300px;
    transition: width 0.25s;    
}

Is there a way to fix the width of a text field to, for example 200px only, and have the height of the text field grow if a user adds more text than the 200px is able to contain? I would like more rows to be added, if a user needs more room to type... so I need the height, not the width, to resize dynamically.

Thanks!

As others explained, input field can't have multiline text, you should use textarea to mimic an input field, and jQuery to make it auto resize vertically (with fixed width).

JS:

//This span is used to measure the size of the textarea
//it should have the same font and text with the textarea and should be hidden
var span = $('<span>').css('display','inline-block')
                      .css('word-break','break-all')
                      .appendTo('body').css('visibility','hidden');
function initSpan(textarea){
  span.text(textarea.text())
      .width(textarea.width())
      .css('font',textarea.css('font'));
}
$('textarea').on({
    input: function(){
       var text = $(this).val();      
       span.text(text);      
       $(this).height(text ? span.height() : '1.1em');
    },
    focus: function(){           
       initSpan($(this));
    },
    keypress: function(e){
       //cancel the Enter keystroke, otherwise a new line will be created
       //This ensures the correct behavior when user types Enter 
       //into an input field
       if(e.which == 13) e.preventDefault();
    }
});

CSS:

textarea {
  width:200px;
  resize:none;
  overflow:hidden;
  font-size:18px;
  height:1.1em;
  padding:2px;
}
Demo.
Updated Demo:

This new updated demo has some bugs fixed and it also supports Enter key, max-height limit, the width does not need to be set fixedly at first (instead we can set its min-width). It's much more full-featured.

Updated Demo

HTML input height Attribute, Example. Define an image as the submit button, with height and width attributes: <form action="/action_page.php"> <label for="fname">First name:</label> // Get a reference to the textarea element var editorStyle = document. getElementById ("editorStyle"); // Add an event listener to trigger a callback on keyup editorInput. addEventListener ("keyup", function (e) {// Set the rows attribute of the textarea to the current number of lines of text // This is done by splitting the current value on newline characters and getting the length of the

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/

Auto-Growing Inputs & Textareas, By default, <input> and <textarea> elements don't change size based on the What about the idea that form data is often serialized and sent along, while the  The gist of it is that you place your textarea inside a wrapper div, set the textarea height to 100% so that it fills the parent, and then insert a div behind the textarea that maintains a copy of the textarea text. The browser will correctly size the hidden div, which will stretch the parent and stretch the textarea.

Not mine but works great:

CSS

textarea {
     color: #444;
     padding: 5px;
}
.txtstuff {
    resize: none;
    overflow: hidden;
}
.hiddendiv {
    display: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word
}
.common {
    width: 500px;
    min-height: 50px;
    font-family: Arial, sans-serif;
    font-size: 13px;
    overflow: hidden;
}
.lbr {
    line-height: 3px;
}

HTML

<textarea id="comments" placeholder="Type many lines of texts in here and you will see magic stuff" class="common"></textarea>

SCRIPT

let txt = $('#comments'),
    txt.addClass('txtstuff');
let hiddenDiv = $(document.createElement('div')),
    hiddenDiv.addClass('hiddendiv common');
let content = null;

$('body').append(hiddenDiv);

txt.on('keyup', function () {
    content = $(this).val();
    content = content.replace(/\n/g, '<br>');
    hiddenDiv.html(content + '<br class="lbr">');
    $(this).css('height', hiddenDiv.height());
});

FIDDLE

Automatically expand a textarea as the user types using vanilla , Automatically expand a textarea as the user types using vanilla JavaScript A max-height of 50vh ensures the text area will never grow bigger than We'll use event delegation to listen to all input events and then filter out  Allowing Excel to automatically change row height When you export a document that contains a Grid/Graph to Excel, sometimes the data can be too long to fit inside an Excel cell. The text wraps within the cell, but the row is too short and cuts off the text.

How to create auto-resize textarea using JavaScript/jQuery , Create a textarea and the task is to automatically resize it when we type or paste the content in it. Method 1: Using JavaScript: To change the height, a new function is created which This will trigger the textarea to resize whenever any text input is detected, therefore last_page How to dynamically load JS inside JS ? The key to making the text fields grow to accommodate text is to: 1. Make them multiline (Object palette > Field tab > Allow multiline property). 2. Make them expandable in height (see “Making a Field Expandable” here). 3.

Expanding Text Areas Made Elegant – A List Apart, An expanding text area is a multi-line text input field that expands in height to fit its you can extend this to do funky stuff such as syntax highlighting as you type;​  This is pretty good, although not flawless. The “expand on click/focus” example grew much taller than it needed to be (at least on my Chrome/Windows 10 browser). The “expand as you type” example is better behaved although it sometimes has a blank line at the end and sometimes not (seems to depend on the text being entered).

Textarea auto-expand, Auto-height textarea using as minimum JS as possible. <textarea rows='1' placeholder='Auto-Expanding Textarea'></textarea>. 4. ​. 5. ​. The height attribute specifies the height of the <input> element. Note: The height attribute is used only with <input type="image">. Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded.

Comments
  • you mean textarea? flaviusmatis.github.io/flexibleArea.js
  • Hi. Nope, not a textarea... I'm wondering if a single-line input type="text" is able to grow (similar to a textarea). Maybe, though, is textarea the only way to go? Perhaps textarea is a solution, but can it be styled to look like a regular text field at the start?
  • Fairly certain you cannot have a multi-line input type of text, that's what textarea is for. You can modify textarea to look like an input field.
  • Thanks... but, I'm actually looking to expand the height of the text field.
  • @Berklie jsfiddle.net/APe4V Its not possible as others have said. You can not have line breaks in input fields.
  • well, +1 for the updated code, however looks like it can just grow, it can't shrink.
  • @KingKing Hi, thank you for your observation. i just fixed it. it was because scrollHeight is always equal to height. then we have to set height '1' before set scrollHeight. jsfiddle.net/mJMpw/551
  • @LGVentura well, looks like it's the best approach I couldn't believe. Although the technique using some dummy element (as shown in my answer) is very well-known and sometimes the only possible way but in this case it's the long way to go. In fact the height can be reset to any value between 0 and 1em, really really interesting solution. this should have been accepted as the answer by the OP.