YakovL YakovL - 11 months ago 49
HTML Question

How to get accurate width of the text inside an HTML input?

So, I have an

and I want it to adjust its
to its content. For now, I use the code like this:

var adjustWidthToContent = function()
var inputLength = $(this).val().length;
// the minimum 1em width allows to start typing when the input is empty
$(this).width(Math.max(1, inputLength*0.7) + "em");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type='text' />

This works ok for desktop, but I'd like to make this more accurate (the 0.7 coefficient is a "hacky" one and the one which calculates the real width is obviously different for different symbols). Try to type multiple symbols: you'll see that the gap grows. Fixing that will be especially helpful for mobile interface where I don't want any extra space get occupied by the empty part of the

Obviously, I need to use something different than
. How do I get the "actual" width of the text inside the

PS here's what I used, based on suggestions:

$.fn.textWidth = function () {
if (!$.fn.textWidth.fakeEl)
$.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(this.val() || this.text()).css('font', this.css('font'));
return $.fn.textWidth.fakeEl.width();
var adjustWidthToContent = function()
var textWidth = jQuery(this).textWidth();
var defaultWidth = 20;
$(this).width( (textWidth || defaultWidth) + 'px');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type='text' />

PPS this does need some elaboration for
to be applicable so several text fields, though.

Answer Source

The solution is to create a fake span, put the inputted text inside, get the size of this span and apply to your input box.

I put 7px more to make room for the " " when the user press "space" to go to another word and the input won't suffer.

I also defined that the default size for the input will be 50px if there's nothing inside.


<input id="my-input" type='text' />


$.fn.textWidth = function (text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();

$('#my-input').on('input', function () {
    var textWidth = $(this).textWidth();
    var defaultValue = 50;
    $('#' + this.id).width( (textWidth == 0 ? defaultValue : textWidth + 7)  + 'px');

I did this following one of the answers of this post: Calculating text width

Hope it helps you! Cheers