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.)
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.)
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')
});
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();