How do I auto-resize the input type="text" field with jQuery? I want it to be like 100px wide at the start, then make it auto-widening as user inputs text... is that possible?
Here's a plugin that'll do what you're after:
The plugin:
(function($){ $.fn.autoGrowInput = function(o) { o = $.extend({ maxWidth: 1000, minWidth: 0, comfortZone: 70 }, o); this.filter('input:text').each(function(){ var minWidth = o.minWidth || $(this).width(), val = '', input = $(this), testSubject = $('<tester/>').css({ position: 'absolute', top: -9999, left: -9999, width: 'auto', fontSize: input.css('fontSize'), fontFamily: input.css('fontFamily'), fontWeight: input.css('fontWeight'), letterSpacing: input.css('letterSpacing'), whiteSpace: 'nowrap' }), check = function() { if (val === (val = input.val())) {return;} // Enter new content into testSubject var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>'); testSubject.html(escaped); // Calculate new width + whether to change var testerWidth = testSubject.width(), newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < o.maxWidth); // Animate width if (isValidWidthChange) { input.width(newWidth); } }; testSubject.insertAfter(input); $(this).bind('keyup keydown blur update', check); }); return this; }; })(jQuery);
EDIT: Found on: Is there a jQuery autogrow plugin for text fields?
I don't think there is a perfect solution to that problem because you cannot detect the actual width of the text entered to the input element. It all depends of the font you are using, zoom settings in browser etc.
However if you can choose a font where you can actually calculate the number of pixels that text have (this is the hardest part but I guess you can try to estimate it somehow). You can use this to change the width of your input field.
$('input').keyup(function () { // I'm assuming that 1 letter will expand the input by 10 pixels var oneLetterWidth = 10; // I'm also assuming that input will resize when at least five characters // are typed var minCharacters = 5; var len = $(this).val().length; if (len > minCharacters) { // increase width $(this).width(len * oneLetterWidth); } else { // restore minimal width; $(this).width(50); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With