How to adjust the width of the input field to its input value with JavaScript?

Spread the love

Sometimes, we want to adjust the width of the input field to its input value with JavaScript.

In this article, we’ll look at how to adjust the width of the input field to its input value with JavaScript.

How to adjust the width of the input field to its input value with JavaScript?

To adjust the width of the input field to its input value with JavaScript, we listen to the input event.

For instance, we write

const input = document.querySelector("input");

const resizeInput = () => {
  input.style.width = `${input.value.length}ch`;
};

input.addEventListener("input", resizeInput);

resizeInput();

to select the input with querySelector.

Then we define the resizeInput function that gets the length of the input value and set that as the width of the input.

ch stands for number of characters.

Next, we add resizeInput as the input event listener.

And then we call resizeInput to resize the input immediately.

Conclusion

To adjust the width of the input field to its input value with JavaScript, we listen to the input event.

Leave a Reply

Your email address will not be published. Required fields are marked *