All those solutions based on number of characters are quite weak, because each character could be of a different width if it is not a monotype font. I'm solving this problem with creating a div containing value of text input with the same font properties and getting its width as a required one.
Something like this:
function resizeInput() {
$('body').append('<div class="new_width">'+$(this).val()+'</div>');
$(this).css('width', $('.new_width').width());
$('.new_width').remove()
}
$('input')
// event handler
.keyup(resizeInput)
// resize on page load
.each(resizeInput);
$('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);
});
$('#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
All those solutions based on number of characters are quite weak, because each character could be of a different width if it is not a monotype font. I'm solving this problem with creating a div containing value of text input with the same font properties and getting its width as a required one.
Something like this:
You can check this demo on js fiddle ... http://jsfiddle.net/ninadajnikar/bzBdX/9/ .
You update the width values as you like it
Here is the jQuery code :
http://jsfiddle.net/bzBdX/7/
Something simple :
You could change the multiplier on personal preference / text-size
Example : http://jsfiddle.net/bzBdX/6/
http://jsfiddle.net/bzBdX/11/
So i made an example where it tries to calculate the width by inserting letters in a span and calculating there width
Theres probably a much better way of doing this.