Get input text width when typing

Viewed 21022

I have a input type text

<input type="text" id="txtid">

When i start typing text inside input, i should be able to get the lenght of the entered text.

This is what I tried:

document.getElementById("txtid").offsetWidth;

and

var test = document.getElementById("txtid");
var width = (test.clientWidth + 1) + "px";

These two does not give the width of the text entered

Basically what I want is:

enter image description here

For suppose input text width is 320px. I need the width of the entered text i.e 120px, which keeps on changing when I enter.

5 Answers

Using the above solution, I turned it into a single function.

let getWidth = (fontSize, value) => {
  let div = document.createElement('div');
  div.innerText = value;
  div.style.fontSize = fontSize;
  div.style.width = 'auto';
  div.style.display = 'inline-block';
  div.style.visibility = 'hidden';
  div.style.position = 'fixed';
  div.style.overflow = 'auto';
  document.body.append(div)
  let width = div.clientWidth;
  div.remove();
  return width;
};
getWidth('10px', 'test');
Related