Michael Swarts
Michael Swarts

Reputation: 3921

Growing text box based on width of characters input

I am trying to create a text box that grows every time a letter is added to it by the width of the character. This is what I'm trying. It doesn't work. If you've got a hint, please share!

JavaScript:

function MakeWidth(el) {
        el.style.width = parseFloat(el.value.clientWidth) }

HTML:

<input id="Test" type="text" style="width: 10px;" onkeyup="MakeWidth(this)"/>

Upvotes: 3

Views: 1804

Answers (3)

kennebec
kennebec

Reputation: 104840

It may be more useful to use the size attribute.

<input id="Test" type="text" size="1" onkeyup="MakeWidth(this)"/>
<script>
function MakeWidth(el) {
        el.size = el.value.length

}
</script>

Upvotes: 3

Martin.
Martin.

Reputation: 10539

Try size & length instead of clientWidth & width

http://jsfiddle.net/eVd9b/5/

function MakeWidth(el) {
    el.size = parseInt(el.value.length);
}

which should be suitable for your needs.

Upvotes: 8

psalvaggio
psalvaggio

Reputation: 181

That's a bit tricky since you don't necessarily know the width of each character. One little trick that comes to mind is that you could try creating a hidden div with the typed character, grab it's width, add it to the textbox width and destroy the hidden div.

Upvotes: 1

Related Questions