JavaScript Auto Increase width of input field

In this tutorial we will learn how to Auto Increase width of input field with JavaScript. HTML DOM style property, length property and CSS unit ch are used to adjust the width of input element with the text.

style property

style property returns the value of HTML element style attribute.

In this example we have used style property to set the width of input field.

ch unit

ch is a CSS unit like px but it sets the width of element relative to width of "0".

In this example we will use ch unit of CSS to set the width of input field. As soon as the number of characters reaches the width of input field, the width will start increasing in real time.

See the example below to understand this.


HTML Code is given below, in this code we have a input tag with oninput event.

CSS is used to set the width of input field to 10ch, it means equal to the width of 10 characters.

<!DOCTYPE html>
<title>JavaScript Auto increase width of input field</title> 
width: 10ch;
max-width: 100%;    
<input type="text" oninput="increaseWidth(this)">
<script src="script.js"></script>    

JavaScript Code

Take a look at the JavaScript code, In this code user defined function increaseWidth() will auto increase the width of input tag, on typing.

length property is used to count number of characters typed inside input tag.

As soon as the 11th character is typed the width of input field is increased by 1ch automatically.

function increaseWidth(x)
    var numberOfCharacters = x.value.length;
    if(numberOfCharacters >= 10)
      var length = numberOfCharacters + "ch"; = length;

This code will also auto decrease the width when characters are deleted from the input field until width is back to 10ch.


Video Tutorial

Watch video tutorial on How To Increase width of input field automatically using JavaScript.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript