tags:

views:

6194

answers:

6

Hi, 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?

A: 

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.

 // 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 live characters
 // are typed
 var minCharacters = 5;

 $('input').keyup(function () {
     var len = $(this).val().length;
     if (len > minCharacters) {
         // increase width
         $(this).width(len * oneLetterWidth);
     } else {
         // restore minimal width;
         $(this).width(50);
     }
 });
RaYell
A: 

By default, input width is controlled by the size parameter, which for type="text" corresponds to number of characters wide it should be.

Since this is measured in characters and not pixels, the actual pixel size is controlled by the (fixed-width) font in use.

R. Bemrose
If you set up a width for the input in CSS when changing the size parameters will not have any effect on the actual element width.
RaYell
+5  A: 

Here's a plugin that'll do what you're after:

See a demo here: http://jsbin.com/ahaxe

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, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                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: http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields

seize
+1  A: 

Hi,

I'm sorry to ask such stupid question but I have never seen the way this is coded before. What does the '(jQuery);' at the end do?

Or what I really asking is, can I put the above function inside $(document).ready(function()?

Best regards - Jon

Jon
It makes sure that this plugin is bound for jQuery only, in case of multiple libraries included in the page, Since other libraries also use the `$` sign it makes sure that this Plugin is bound to jQuery, It does it via a closure.
adardesign
A: 

Hello I dont know if you are still looking but i came across this when i was looking for a script to do the same thing. So hope this helps anyone who is trying to do this, or something similar.

function editing_key_press(e){ if(!e.which)editing_restore(this.parentNode); var text = $('') .html($(this).val()) .appendTo(this.parentNode); var w = text.innerWidth(); text.remove(); $(this).width(w+10); }

The logic to this code is to put the content onto the page in a span and then gets the width of this content and removes it. The problem i did have was with it was that i had to get it to run on both keydown and keyup for it to work successfully.

Hope this helps, Might not as i have only been doing jquery for a short amount of time.

Thanks

George

thor222
A: 

Hi,

Here you can find a JQuery plugin for auto sizing a text field

All the best, Laurentiu

Laurentiu