Sometimes, we may want to adjust the width of an input field to the width of its input value.
In this article, we’ll look at how to adjust the width of an input field to the width of its input value.
Listen to the keypress Event
We can listen to the keypress
event to get the input value on keypress.
Then we can set the style.width
property of the input to the width of the input value.
To do this, we write the following HTML:
<input type="text">
And the following JavaScript:
const input = document.querySelector('input')
input.addEventListener('keypress', (e) => {
input.style.width = `${e.target.value.length}ch`
})
We get the input element with querySelector
.
Then we call addEventListener
with 'keypress’
to listen to the keypress event.
In the event handler callback, we set input.style.width
to the e.target.value.length
with unit in ch
.
e.target.value
has the value inputted into the input box.
ch
is the width of the 0 character of the element’s font.
Now when we type in the input, we should see the input box lengthen to the width of the input value as we type stuff in.
Conclusion
We can set an input element’s width to the width of the inputted value setting the width of the input in ch
.