How to Adjust the Width of Input Field Automatically using JavaScript?
The <input> element in HTML is used to create interactive controls for forms, allowing users to input data. It is one of the most versatile elements, with various input types and attributes that make it powerful for building forms. One important attribute is the width attribute, which allows you to control the width of the input field.
1. Using onkeypress
Event in JavaScript
The onkeypress
event triggers when the user presses a key. By tracking the input length with this.value.length
, we can dynamically adjust the width of the <input>
element to match the length of the value entered by the user.
- Use the
onkeypress
event on the<input>
element. - Track the length of the input field with
this.value.length
. - Adjust the width of the input dynamically based on the length of the entered text.
<input type="text" onkeypress="myFunction()">
Here, we select the <input> element and add a method to it which occurs when a key is pressed. This method selects and updates the value of the width property dynamically. You can also write a JavaScript function to check the length of your string on input change, then adjust the width of the input based on the number of chars * character width.
<form method="post" action="">
<label for="username">Input text</label>
<input type="text" id="textbox" name="textbox"
placeholder="Welcome" onkeypress="this.style.width =
((this.value.length + 1) * 8) + 'px';" id="input" />
</form>
const input = document.querySelector('input');
input.style.width = ((input.getAttribute('placeholder').length + 1) * 8) + 'px';
input.addEventListener('focusout', function() {
if (this.value.length > 0) {
this.style.width = ((this.value.length + 1) * 8) + 'px';
} else {
this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
}
});
Output

2. Using jQuery keypress() Event
The jQuery keypress() event, in combination with String.fromCharCode(e.which), can be used to dynamically increase the width of the input element. This approach calculates the width of the input based on the number of characters entered and adjusts it accordingly.
- Use the jQuery keypress() event to detect keypresses.
- Use String.fromCharCode(e.which) to get the character pressed.
- Dynamically adjust the width of the input field based on the input length.
$('input[type="text"]').keypress(function(e) {
if (e.which !== 0 && e.charCode !== 0) {
// Only characters
var c = String.fromCharCode(e.keyCode|e.charCode);
$span = $(this).siblings('span').first();
// The hidden span takes
$span.text($(this).val() + c) ;
// The value of the input
$inputSize = $span.width() ;
// Apply width of the span to the input
$(this).css("width", $inputSize) ;
}
}) ;
Output