1

http://jsfiddle.net/bDaGV/1/

Is there anyway to set the width of an input text type to be the width of the value inside?

CSS

input[type=text] {
  width:auto;
}

JS:

$('input[type=text]').css('width', $(this).val());
7
  • Are you wanting the input box to expand if the characters inside end up taking up more space than the input? Commented Jan 24, 2014 at 22:56
  • No the size of each input should be the elements value. Commented Jan 24, 2014 at 22:57
  • Yes, but do you want the size to change when you type in the input, thus changing the value ? Commented Jan 24, 2014 at 22:58
  • Oh, I'm with you. One second. Commented Jan 24, 2014 at 22:58
  • Yes (I have to wait 9 minutes before I can accept the answer) Commented Jan 24, 2014 at 22:58

2 Answers 2

2

You could use the size trick

$('input[type=text]').attr('size', function() {
    return this.value.length;
});

FIDDLE

For completeness, to make it "auto expand", you'd need an event handler as well

$('input[type=text]').on('keyup', function() {
    $(this).attr('size', this.value.length);
}).trigger('keyup');

FIDDLE

Sign up to request clarification or add additional context in comments.

4 Comments

Darnit, beat me to it :-P I was typing up the same fiddle hahaha. Upvoted.
don't forget to recommend a monospace font or else "..." will look funny.
I was trying css I didn't think about the size handler. Thanks!
sigh, yet again beat me to it haha. Well done @adeneo.
1

You can hack a span with the contenteditable attribute then style it to look like an input:

<span class="input" contenteditable id="input1">ddd</span>
<style>
  span.input {
    border: thin black solid;
    padding: 2px 6px;
    background-color: #EEE;
  }
</style>

Given jQuery, it's easy to get that text with something like $('#input1').text();

Here's a fiddle: http://jsfiddle.net/JoeAndrieu/qYpAK/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.