Auto-scaling input[type=text] to width of value?

css, html, jquery

Solution

You can do this the easy way by setting the `size` attribute to the length of the input contents:

function resizeInput() {
    $(this).attr('size', $(this).val().length);
}

$('input[type="text"]')
    // event handler
    .keyup(resizeInput)
    // resize on page load
    .each(resizeInput);

See: http://jsfiddle.net/nrabinowitz/NvynC/

This seems to add some padding on the right that I suspect is browser dependent. If you wanted it to be really tight to the input, you could use a technique like the one I describe in this related answer, using jQuery to calculate the pixel size of your text.

Problem

Is there a way to scale the width of an `<input type="text">` to the width of the actual value? ``` input { display: block; margin: 20px; width: auto; } ``` ``` <input type="text" value="I've had enough of these damn snakes, on this damn plane!" /> <input type="text" value="me too" /> ```

Original source

Related problems