Open In App

How to Adjust the Width of Input Field Automatically using JavaScript ?

Last Updated : 16 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user. The <input> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. The HTML <input> width attribute is used to specify the width of the element.

To increase the width of <input> element dynamically.
Approach 1:

  • The onkeypress event occurs when the user presses any key.
  • Select the width attribute of an element.
  • Make it equal to the length of the value of the input field by this.value.length
<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.

HTML Code:




<!DOCTYPE html> 
<html> 
<head> 
    <title> How to adjust width of 
an input field to its input?</title> 
</head> 
<body> 
    <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>
</body> 
</html>                 


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.

Alternative JavaScript Code:




$('input').css('width', ((
  input.getAttribute('placeholder').length + 1) * 8) + 'px');
$("input").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:

Approach 2: Use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence, we can calculate the width of the input element.

jQuery Code:




$('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:

Browser Compatibility:

  • Chrome: Yes
  • Firefox: Yes (63.0)
  • Edge: Yes
  • Internet Explorer: Yes
  • Opera: Yes
  • Safari: Yes


Similar Reads

How to validate if input in input field has full width string only using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only full-width strings are allowed. We can also validate these input fields to only accept full-width s
5 min read
How to set focus on input field automatically on page load in AngularJS ?
We can focus on any input field automatically using the angular directives. Here we create a custom directive that can auto-focus on any field in the form. Creating a custom directive is just like creating an Angular component. To create a custom directive we have to replace @Component decorator with @Directive decorator. Approach : Create the Angu
3 min read
How to fill all input fields automatically from database by entering input in one textbox using PHP ?
XAMPP is a free and open-source cross-platform web server solution developed by Apache Friends, consisting mainly of the Apache HTTP Server, MySQL database, and interpreter for scripts written in the PHP programming language. The XAMPP server helps to start Apache and MySQL and connect them with the PHP file. Approach: We need to create a MySQL dat
4 min read
How to adjust the width and height of iframe to fit with content in it ?
Using iframe tag the content inside the tag is displayed with a default size if the height and width are not specified. thou the height and width are specified then also the content of the iframe tag is not displayed in the same size of the main content. It is difficult to set the size of the content in the iframe tag as same as the main content. S
3 min read
How to validate if input date (end date) in input field must be after a given date (start date) using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come after some given date(Ex. 'end date' must be after 'start date')
5 min read
How to validate if input in input field exactly equals to some other value using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type some exact value and based on that we give the user access to the request or deny the r
5 min read
How to validate if input in input field has alphanumeric characters only using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only alphanumeric characters are allowed i.e. there not allowed any special characters. We can also vali
4 min read
How to validate if input in input field has base64 encoded string using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not const
5 min read
How to validate if input in input field has boolean value using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only boolean value i.e. true or false are allowed. We can also validate these input fields to accept onl
4 min read
How to validate if input in input field has base 32 encoded string using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field, only base 32 encoded strings are allowed i.e. there not allowed any other form of string which does n
5 min read