☰ autosizeInput
 

Autosize Input

Le CSS:

.input-element {
  border: 0;
  padding: 2px;
  background: #fff;
  font: 12pt sans-serif;
}

.tmp-element {
  visibility: hidden;
  white-space: pre;
}

Le HTML:

<input id="theInput" type="text" class="input-element" value="1">

Le JAVASCRIPT:

var inputEl = document.getElementById("theInput");

function getWidthOfInput() {
  var tmp = document.createElement("span");
  tmp.className = "input-element tmp-element";
  tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  document.body.appendChild(tmp);
  var theWidth = tmp.getBoundingClientRect().width;
  document.body.removeChild(tmp);
  return theWidth;
}

function adjustWidthOfInput() {
  inputEl.style.width = getWidthOfInput() + "px";
}

adjustWidthOfInput();
inputEl.onkeyup = adjustWidthOfInput;

Exemple