Make an entry to fit your text

I have tried different ways to make an input adapt to is text. The closer I get with jQuery is: $("div").attr("size", $("div").val().length );

I think this works with the attribute size, but this does not seem to measure very well the text. It seems that size works well to measure numbers but not text:

So, when I use size with jQuery:

$("#jQ").attr("size", $("#jQ").val().length );


Here is the example to play:

Is there a better way to make an input adapt to its text?

Unless you’re using a monotype font where all the characters have the same width, the easiest way to get the width of a string is to append it to an element, and get the width of the element, like this

$("#jQ").css('width', function() {
    var el = $('', {
        text : this.value,
        css  : {left: -9999, position: 'relative'}
    var w = el.css('width');
    return w;

Note that setting the height and width of an element doesn’t really do anything unless the element has position and is not static.


To make the width follow the keys as they are pressed, you’d just wrap that in an event handler


Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Make an entry to fit your text

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录