0

I want to know the width of the actual text in the input box, not the input box. Is there an equivalent of

$('#mybox').val().width();

that measures exactly how many pixels the text takes up? (This code obviously would not work.)

mango
  • 1,183
  • 6
  • 17
  • 33

2 Answers2

1

Something like this

$('input').on('keyup', function() {
    var el = $('<div />', {
        text : this.value, 
        css  : {display : 'table-cell'}
    }).appendTo('body');

    var computedStyle = typeof this.currentStyle != 'undefined' ? 
            this.currentStyle : 
            document.defaultView.getComputedStyle(this, null);

    $.each(computedStyle, function(_, style) {
        if (style.indexOf('display') == -1 && style.indexOf('width') == -1)
            el.get(0).style[style] = computedStyle[style];
    });

    var w = el.prop('clientWidth');
    $(el).remove()

    $('#width_output').html(w + 'px')
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Got this from here: Calculate text width with JavaScript

String.prototype.width = function(font) {
  var f = font || '12px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

Now you can use:

$('#mybox').val().width();
Community
  • 1
  • 1
Stefan
  • 2,961
  • 1
  • 22
  • 34