I see two ways.
First:
You can use a div with content editable instead input. Like this you can see the width of the div.
var elemDiv = document.getElementById('a');
elemDiv.onblur = function() {
console.log(elemDiv.clientWidth + 'px');
}
div {
width: auto;
display: inline-block;
}
<div id='a' contenteditable="plaintext-only">Test</div>
Note : Like @Leon Adler say, this way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.
Second:
Use an input type text and paste the content into an invisible div. And you can see the width of the invisible div.
var elemDiv = document.getElementById('a'),
elemInput = document.getElementById('b');
elemInput.oninput = function() {
elemDiv.innerText = elemInput.value;
console.log(elemDiv.clientWidth + 'px');
}
.div {
width: auto;
display: inline-block;
visibility: hidden;
position: fixed;
overflow:auto;
}
<input id='b' type="text">
<div id='a' class="div"></div>
Note : For this way, you must have the same font and font size on input
and div
tags.