March 12, 2012

How to increase width of textfield according to typed text?

Question by manishjangir

I want to increase the width of input text field automatically if a user inputs some text in it. But how to do it. Please help me.Can it be using Jquery or javascript

Thanks.

Answer by MatuDuke

Try with this:

<script>
function adjustWidth(obj) {

    obj.style.width = (obj.value.length) * 7.3 + "px";
}
</script>
<input type="text" onkeypress="adjustWidth(this)">

However this depends on text size, font, etc

Answer by Starx

The width cannot be increased as precisely as the width of character vary from one another.

But still, you can do something like this

$("input:text").keyup(function() {
    $(this).css('width', $(this).val().length*10);
});

Demo
As you can see I am assuming that for every character the field size has to be increased by 10px. This is very hard to assign a correct ration that fits all the characters.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!