Resize the content input box

Trying to get my input fields [type = 'text'] to resize their content on page load. Using this code, they effectively resize on focus .

$(document).ready(function () { $("input[type='text']").bind('focus', function () { $(this).attr("size", $(this).val().length ); }); });

I've tried replacing "focus" with different events like "loading" and "ready" to no avail. Keep in mind that I'm looking for something light and fast that will resize all [type = 'text'] input fields to their contents on page load.

JSFIDDLE


Decision

I ended up using Thom as a solution, but then realized that I also needed the input box to expand as I entered text into it. So I merged what I had before and Tom responded to provide both. I also added css to make sure it is not page size. Here is my final code:

Html
<input type="text" value="resized onload and when typing"/>

JQuery
$(document).ready(function () { $("input[type='text']" ).each(function( index ) { $(this).attr("size", $(this).val().length + 5 ); }); $("input[type='text']").bind('keyup', function () { $(this).attr("size", $(this).val().length + 5); }); });

CSS
input[type="text"]{ max-width:100%;}

JSFIDDLE

+3


source to share


2 answers


Go through them to the house ready:

jQuery(document).ready(function($)
{
    $("input[type='text']").each(function()
    {
        $(this).attr("size", $(this).val().length);
    });
});

      



Fiddle

+1


source


If the value is set, you can use this:

$(document).ready(function () {

    $('input[type="text"]').each(function(){
        $(this).attr('size', $(this).attr('value').length);
    });

});

      

If you want to resize while typing, add this:



$("input[type='text']").on('input', function () {
   $(this).attr("size", $(this).val().length );
   console.log($('input[type="text"]').attr('size'));
});

      

Remember that "size" represents the number of characters inside your inputs. The actual width depends on the font size you are using and the size of your input. (just for sure :)

+1


source







All Articles