KDD
KDD

Reputation: 75

Auto fitting text in a textbox

Can't seem to find out to do this in either html or JS (or maybe even jquery?).

I have a text-box that echo's whatever is typed into it in an input box more down the page. This echo box needs to auto-fit to whatever text is inside it so that it doesn't have this huge white space spot after the text.

Any ideas how to auto-fit a input field to text that is inserted into it?

Upvotes: 0

Views: 1004

Answers (1)

Shmiddty
Shmiddty

Reputation: 13967

I think you're looking for something like this: http://jsfiddle.net/ener3/

$("#in").keyup(function(){
  var tmp = $("<span>")
            .text(this.value)
            .css("font", $("#out").css("font"))
            .appendTo("body"),
      wid = tmp.width();
  tmp.remove();

  $("#out").val(this.value).width(wid);
});

where #in is the id of the input, and #out is the textbox you want to autosize.

You can add this to the head of the page like so:

<script type="text/javascript">
$(function(){
    // paste the above code here
});
</script>

Make sure you put the script tag after your jQuery include:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

You can replace 1.8.3 with the version of jQuery you want to target. I wouldn't recommend using jQuery-latest to start as you'd have to account for potential deprecation where applicable.

Upvotes: 1

Related Questions