Dynamically Expand Height of Input Type "Text" Based on Number of Characters Typed into Field

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

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

Adjust width of input field to its input

It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:

<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

Note: this solution only works when every character is exactly 8px wide. You could use the CSS-Unit "ch" (characters) which represents the width of the character "0" in the chosen font. You can read about it here.

dynamically increase input type text textbox width according to the characters entering into it

I have tried this code and it works fine.

<html>
<head>
<script type="text/javascript">
function Expand(obj){
if (!obj.savesize) obj.savesize=obj.size;
obj.size=Math.max(obj.savesize,obj.value.length);
}
</script>
</head>
<body>
<form>
<input type="text" size="5" style="font-family:Courier;" onkeyup="Expand(this);">
</form>
</body>
</html>

Be sure to use mono space fonts in text box, otherwise the size attr. and number of characters won't match

autoresize textarea field after entering text dynamically

http://www.jacklmoore.com/autosize

May be what you need and add a max-height to the text-area CSS.



Related Topics



Leave a reply



Submit