Is it possible to get input\'s value width and resize the input dynamically so the value will fit?
Here\'s an example:
http://jsfiddle.net/bzBdX/2/
Something simple :
$('#resizeme').keydown(function(){ // listen for keypresses
var contents = $(this).val(); // get value
var charlength = contents.length; // get number of chars
newwidth = charlength*9; // rough guesstimate of width of char
$(this).css({width:newwidth}); // apply new width
});
You could change the multiplier on personal preference / text-size
Example : http://jsfiddle.net/bzBdX/6/
You can check this demo on js fiddle ... http://jsfiddle.net/ninadajnikar/bzBdX/9/ .
You update the width values as you like it
I have a jQuery plugin on GitHub: https://github.com/MartinF/jQuery.Autosize.Input
It mirrors the value of the input so it can calculate the actual length instead of guessing or other approaches mentioned.
You can see an live example here: http://jsfiddle.net/jw9oqz0e/
Example:
<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 40 }' />
input[type="data-autosize-input"] {
width: 90px;
min-width: 90px;
max-width: 300px;
transition: width 0.25s;
}
You just use css to set min/max-width and use a transition on the width if you want a nice effect.
You can specify the space / distance to the end as the value in json notation for the data-autosize-input attribute on the input element.
Of course you can also just initialize it using jQuery
$("selector").autosizeInput();
$(function(){
$("input").keyup(function(){
$(this).stop().animate({
width: $(this).val().length*7
},100)
})
})
Here is the jQuery code :
$('input').each(function(){
var value = $(this).val();
var size = value.length;
// playing with the size attribute
//$(this).attr('size',size);
// playing css width
size = size*2; // average width of a char
$(this).css('width',size*3);
});
http://jsfiddle.net/bzBdX/7/
Current answers were waay to complicated. Heres a quick one
$('#myinput').width($('#myinput').prop('scrollWidth'))
Adding the above to input keydown/up/press events is trivial. Tested in chrome