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.
Table of Contents
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
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>
<html>
<head>
<title>JavaScript Auto increase width of input field</title>
<style>
input
{
width: 10ch;
max-width: 100%;
}
</style>
</head>
<body>
<input type="text" oninput="increaseWidth(this)">
<script src="script.js"></script>
</body>
</html>
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.
<script>
function increaseWidth(x)
{
var numberOfCharacters = x.value.length;
if(numberOfCharacters >= 10)
{
var length = numberOfCharacters + "ch";
x.style.width = length;
}
}
</script>
This code will also auto decrease the width when characters are deleted from the input field until width is back to 10ch.
Demo
Video Tutorial
Watch video tutorial on How To Increase width of input field automatically using JavaScript.