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)"/>
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)"/>
Share
Improve this question
asked Nov 13, 2011 at 19:52
Michael SwartsMichael Swarts
3,9218 gold badges36 silver badges46 bronze badges
3 Answers
Reset to default 8Try size
& length
instead of clientWidth
& width
http://jsfiddle/eVd9b/5/
function MakeWidth(el) {
el.size = parseInt(el.value.length);
}
which should be suitable for your needs.
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>
That's a bit tricky since you don't necessarily know the width of each character. One little trick that es 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.