2

I have an <input type="text" /> tag.

There may be too much content in it, and when the content length goes exceed the input width, it will be scrolling horizontally.

In fact, I want to control the width of tag, to make it varying according to the content.

So, is there any way to get the content width of the tag? Similar to the scrollHeight attribute?

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189

3 Answers3

8

check this out

http://jsfiddle.net/philfreo/MqM76/

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

Calculating text width

Community
  • 1
  • 1
divakar
  • 1,379
  • 6
  • 15
  • 31
0

You can use $("#chkText").on('input', function (){}); as below

JSFiddle Here

<script type="text/javascript">
    $(document).ready(function () {
        $("#chkText").on('input', function () {
            var lng = $("#chkText").val().length;
            $("#chkText").width(lng * 10);
        });
    });
</script>

HTML

<input type="text" id="chkText"/>
Garric
  • 552
  • 3
  • 13
  • 29
prog1011
  • 3,425
  • 3
  • 30
  • 57
0

Try to adjust the length onkeypess or onkeyup:

A onkeypress example. onkeypress="this.style.width = ((this.value.length + 1) * 5) + 'px';"

This should work if you put it inside the input tag. I think it would be good to define a minimum/maximum width.

Marcus Rommel
  • 1,266
  • 1
  • 12
  • 17