Adjust width of input field to its input












124















<html>
<head>
</head>
<body>
<input type="text" value="1" style="min-width:1px;" />
</body>
</html>


This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?



I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.



If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.










share|improve this question





























    124















    <html>
    <head>
    </head>
    <body>
    <input type="text" value="1" style="min-width:1px;" />
    </body>
    </html>


    This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?



    I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.



    If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.










    share|improve this question



























      124












      124








      124


      36






      <html>
      <head>
      </head>
      <body>
      <input type="text" value="1" style="min-width:1px;" />
      </body>
      </html>


      This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?



      I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.



      If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.










      share|improve this question
















      <html>
      <head>
      </head>
      <body>
      <input type="text" value="1" style="min-width:1px;" />
      </body>
      </html>


      This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?



      I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em, that is the problem and second problem is that min-width ain't working on input at all.



      If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.







      javascript html css






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 1 '18 at 23:57









      brasofilo

      21.6k1068140




      21.6k1068140










      asked Aug 2 '10 at 23:11









      KercKerc

      633265




      633265
























          24 Answers
          24






          active

          oldest

          votes


















          72














          It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:



          <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">


          Note: this solution only works when every character is exactly 8px wide.






          share|improve this answer





















          • 22





            @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

            – Marcel Korpel
            Aug 3 '10 at 0:25






          • 6





            I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

            – Tahbaza
            Aug 3 '10 at 0:43






          • 1





            – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

            – Marcel Korpel
            Aug 3 '10 at 11:25






          • 2





            Here is a demo for those interested: jsfiddle.net/73T7S

            – starbeamrainbowlabs
            Jul 2 '13 at 6:39






          • 4





            you have forgotten the PASTE event my friend ;) you should change it to onInput

            – vsync
            Jan 27 '17 at 22:37





















          58














          To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.



          I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.



          BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.



          <!DOCTYPE html>
          <html>
          <head>
          <meta charset="utf-8">
          <title>Get/set width of &lt;input&gt;</title>
          <style>
          body {
          background: #666;
          }

          .input-element {
          border: 0;
          padding: 2px;
          background: #fff;
          font: 12pt sans-serif;
          }

          .tmp-element {
          visibility: hidden;
          white-space: pre;
          }
          </style>
          </head>
          <body>
          <input id="theInput" type="text" class="input-element" value="1">
          <script>
          var inputEl = document.getElementById("theInput");

          function getWidthOfInput() {
          var tmp = document.createElement("span");
          tmp.className = "input-element tmp-element";
          tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
          document.body.appendChild(tmp);
          var theWidth = tmp.getBoundingClientRect().width;
          document.body.removeChild(tmp);
          return theWidth;
          }

          function adjustWidthOfInput() {
          inputEl.style.width = getWidthOfInput() + "px";
          }

          adjustWidthOfInput();
          inputEl.onkeyup = adjustWidthOfInput;
          </script>
          </body>
          </html>





          share|improve this answer


























          • I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

            – Nathan
            Sep 18 '12 at 21:14








          • 9





            You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

            – Timo Kähkönen
            Feb 28 '13 at 23:36











          • @Timo: You're right, thanks.

            – Marcel Korpel
            Mar 1 '13 at 12:27






          • 2





            tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

            – lisak
            Jan 6 '15 at 16:18











          • @lisak Thanks, I adjusted my answer, but there are already better answers here.

            – Marcel Korpel
            Jan 6 '15 at 16:25



















          44














          In modern browser versions, CSS unit ch is also available. To my understanding, it is font-independent unit, where 1ch equals to width of character 0 (zero) in any given font.



          Thus, something as simple as following could be used as resize function:






          var input = document.querySelector('input'); // get the input element
          input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
          resizeInput.call(input); // immediately call the function

          function resizeInput() {
          this.style.width = this.value.length + "ch";
          }

          input{ font-size:1.3em; padding:.5em; }

          <input>





          That example would resize "elem" to length of the value + 2 characters extra.






          share|improve this answer





















          • 7





            I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

            – Husky
            Jun 9 '17 at 19:09











          • I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

            – Lonnie Best
            May 13 '18 at 4:02






          • 4





            This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

            – vsync
            May 16 '18 at 10:25











          • Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

            – Jilles van Gurp
            2 days ago



















          25














          Here's a modification of Lyth's answer that takes into account:




          • Deletion

          • Initialisation

          • Placeholders


          It also allows for any number of input fields! To see it in action: http://jsfiddle.net/4Qsa8/



          Script:



          $(document).ready(function () {
          var $inputs = $('.resizing-input');

          // Resize based on text if text.length > 0
          // Otherwise resize based on the placeholder
          function resizeForText(text) {
          var $this = $(this);
          if (!text.trim()) {
          text = $this.attr('placeholder').trim();
          }
          var $span = $this.parent().find('span');
          $span.text(text);
          var $inputSize = $span.width();
          $this.css("width", $inputSize);
          }

          $inputs.find('input').keypress(function (e) {
          if (e.which && e.charCode) {
          var c = String.fromCharCode(e.keyCode | e.charCode);
          var $this = $(this);
          resizeForText.call($this, $this.val() + c);
          }
          });

          // Backspace event only fires for keyup
          $inputs.find('input').keyup(function (e) {
          if (e.keyCode === 8 || e.keyCode === 46) {
          resizeForText.call($(this), $(this).val());
          }
          });

          $inputs.find('input').each(function () {
          var $this = $(this);
          resizeForText.call($this, $this.val())
          });
          });


          Style:



          .resizing-input input, .resizing-input span {
          font-size: 12px;
          font-family: Sans-serif;
          white-space: pre;
          padding: 5px;
          }


          HTML:



          <div class="resizing-input">
          <input type="text" placeholder="placeholder"/>
          <span style="display:none"></span>
          </div>





          $(document).ready(function() {
          var $inputs = $('.resizing-input');

          // Resize based on text if text.length > 0
          // Otherwise resize based on the placeholder
          function resizeForText(text) {
          var $this = $(this);
          if (!text.trim()) {
          text = $this.attr('placeholder').trim();
          }
          var $span = $this.parent().find('span');
          $span.text(text);
          var $inputSize = $span.width();
          $this.css("width", $inputSize);
          }

          $inputs.find('input').keypress(function(e) {
          if (e.which && e.charCode) {
          var c = String.fromCharCode(e.keyCode | e.charCode);
          var $this = $(this);
          resizeForText.call($this, $this.val() + c);
          }
          });

          // Backspace event only fires for keyup
          $inputs.find('input').keyup(function(e) {
          if (e.keyCode === 8 || e.keyCode === 46) {
          resizeForText.call($(this), $(this).val());
          }
          });

          $inputs.find('input').each(function() {
          var $this = $(this);
          resizeForText.call($this, $this.val())
          });
          });

          .resizing-input input,
          .resizing-input span {
          font-size: 12px;
          font-family: Sans-serif;
          white-space: pre;
          padding: 5px;
          }

          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
          <div class="resizing-input">
          First:
          <input type="text" placeholder="placeholder" />
          <span style="display:none"></span>
          </div>
          <br>








          share|improve this answer


























          • Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

            – Maxence
            Jan 19 '18 at 21:13






          • 1





            @Maxence listening to the change or input event would suffice

            – yarwest
            Aug 6 '18 at 14:10











          • I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

            – jayt
            Aug 21 '18 at 9:59











          • Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

            – Maxence
            Oct 12 '18 at 15:20



















          15














          FOR A NICER LOOK&FEEL



          You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)



          Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/



          Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.






          document.querySelector('input').addEventListener('input', onInput)

          function onInput(){
          var spanElm = this.nextElementSibling;
          spanElm.textContent = this.value; // the hidden span takes the value of the input;
          this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
          };

          /* it's important the input and its span have same styling */
          input, .measure {
          padding: 5px;
          font-size: 2.3rem;
          font-family: Sans-serif;
          white-space: pre; /* white-spaces will work effectively */
          }

          .measure{
          position: absolute;
          left: -9999px;
          top: -9999px;
          }

          <input type="text" />
          <span class='measure'></span>








          share|improve this answer





















          • 1





            Looks nice, but it doesn't take Backspace and Delete into account.

            – Marcel Korpel
            Mar 1 '13 at 12:31











          • Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

            – Lyth
            Mar 3 '13 at 14:21













          • If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

            – Frinsh
            May 6 '15 at 12:08













          • I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

            – vsync
            May 16 '18 at 11:04



















          11














          Here is a solution without monospaced font needed, with only very small piece code of javascript, do not need calculate computed styles, and, even support ime, support rtl texts.






          // copy the text from input to the span
          $(function () {
          $('.input').on('input', function () { $('.text').text($('.input').val()); });
          });

              * {
          box-sizing: border-box;
          }

          .container {
          display: inline-block;
          position: relative;
          }

          .input,
          .text {
          margin: 0;
          padding: 2px 10px;
          font-size: 24px;
          line-height: 32px;
          border: 1px solid #ccc;
          box-radius: 3px;
          height: 36px;
          font: 20px/20px sans-serif;
          /* font: they should use same font; */
          }

          .text {
          padding-right: 20px;
          display: inline-block;
          visibility: hidden;
          white-space: pre;
          }

          .input {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          width: 100%;
          }

          <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

          <div class="container">
          <span class="text">
          some text
          </span>
          <input class="input" value="some text" />
          </div>





          Use the span.text to fit width of text, and let the input have same size with it by position: absolute to the container. Copy value of input to the span every time it changed (you may change this piece of code to vanilla js easily). So the input will just "fit" the size of its content.






          share|improve this answer

































            8














            You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.



            An input could dynamically adjust it's size by listening for key events.



            For example



            $("input[type='text']").bind('keyup', function () {
            $(this).attr("size", $(this).val().length );
            });


            JsFiddle here






            share|improve this answer































              7














              You could do something like this



              // HTML
              <input id="input" type="text" style="width:3px" />
              // jQuery
              $(function(){
              $('#input').keyup(function(){
              $('<span id="width">').append( $(this).val() ).appendTo('body');
              $(this).width( $('#width').width() + 2 );
              $('#width').remove();
              });
              });









              share|improve this answer
























              • Only if body > span has the exact same styling as #input...

                – Trevor Burnham
                Jun 15 '12 at 22:31











              • If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                – Lyth
                Feb 13 '13 at 13:35



















              7














              Here is an alternative way to solve this using a DIV and the 'contenteditable' property:



              HTML:



              <div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>


              CSS: (to give the DIV some dimensions and make it easier to see)



              .fluidInput {

              display : inline-block;
              vertical-align : top;

              min-width : 1em;
              height : 1.5em;

              font-family : Arial, Helvetica, sans-serif;
              font-size : 0.8em;
              line-height : 1.5em;

              padding : 0px 2px 0px 2px;
              border : 1px solid #aaa;
              cursor : text;
              }


              .fluidInput * {

              display : inline;

              }


              .fluidInput br {

              display : none;

              }


              .fluidInput:empty:before {

              content : attr(data-placeholder);
              color : #ccc;

              }


              Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.






              share|improve this answer





















              • 1





                This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                – Daniel Bonnell
                Jul 5 '17 at 20:45











              • But it's not an input!

                – Toni Michel Caubet
                May 24 '18 at 17:31



















              4














              Here is a plain JS and a jQuery plugin I wrote that will handle resizing an input element using a canvas and the font size / family to determine the actual string length when rendered. (only works in > IE9, chrome, safari, firefox, opera and most other major browsers that have implemented the canvas element).



              PlainJS:



              function autoSize(input, o) {
              o || (o = {});
              o.on || (o.on = 'keyup');

              var canvas = document.createElement('canvas');
              canvas.setAttribute('style', 'position: absolute; left: -9999px');
              document.body.appendChild(canvas);

              var ctx = canvas.getContext('2d');

              input.addEventListener(o.on, function () {
              ctx.font = getComputedStyle(this,null).getPropertyValue('font');
              this.style.width = ctx.measureText(this.value + ' ').width + 'px';
              });
              }

              //Usage
              autoSize(document.getElementById('my-input'));


              jQuery Plugin:



              $.fn.autoSize = function(o) {
              o = $.extend({}, {
              on: 'keyup'
              }, o);

              var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
              $('body').append($canvas);

              var ctx = $canvas[0].getContext('2d');

              return this.on(o.on, function(){
              var $this = $(this);
              ctx.font = $this.css('font');
              $this.width(ctx.measureText($this.val()).width + 'px');
              })
              }

              //Usage:
              $('#my-input').autoSize();


              Note: this will not handle text-transforms, line spacing and letter spacing, and probably some other text size changing properties. To handle text-transform property set and adjust the text value to match that property. The others are probably fairly straight forward. I will implement if this starts gaining some traction...






              share|improve this answer

































                4














                This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:



                <input [style.width.ch]="value.length" [(ngModel)]="value" />


                It automatically updates via the character units in Jani's answer.






                share|improve this answer































                  2














                  You can do it even simpler in angularjs using the built-in ng-style directive.



                  In your html:



                    <input ng-style="inputStyle(testdata)" ng-model="testdata" />


                  In your controller:



                   $scope.testdata = "whatever";

                  $scope.inputStyle = function(str) {
                  var charWidth = 7;
                  return {"width": (str.length +1) * charWidth + "px" };
                  };


                  In your css:



                  input { font-family:monospace; font-size:12px; }


                  Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;






                  share|improve this answer



















                  • 2





                    This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                    – vlasits
                    Aug 7 '14 at 15:32











                  • How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                    – Ethan
                    May 18 '15 at 15:57











                  • You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                    – Dan Dascalescu
                    Jul 8 '15 at 11:47



















                  2














                  It's worth noting that a nice-looking resize can be done when the font is monospaced, so we can perfectly resize the input element using the ch unit.



                  Also in this approach we can update the width of the field by just updating a CSS variable (custom property) on input event and we should also take care of already pre-filled input on DOMContentLoaded event




                  Codepen demo






                  Markup



                  <input type="text" value="space mono font" class="selfadapt" />


                  CSS



                  :root { --size: 0; }

                  .selfadapt {
                  padding: 5px;
                  min-width: 10ch;
                  font-family: "space mono";
                  font-size: 1.5rem;
                  width: calc(var(--size) * 1ch);
                  }


                  As a root variable we set --size: 0: this variable will contain the length of the input and it will be multiplied by 1ch inside the calc() expression. By default we could also set a min-width, e.g. 10ch



                  The Javascript part reads the length of the value inserted and updates the variable --size:



                  JS



                  let input = document.querySelector('.selfadapt');
                  let root = document.documentElement.style;

                  /* on input event auto resize the field */
                  input.addEventListener('input', function() {
                  root.setProperty('--size', this.value.length );
                  });

                  /* resize the field if it is pre-populated */
                  document.addEventListener("DOMContentLoaded", function() {
                  root.setProperty('--size', input.value.length);
                  });


                  of course this still works even if you don't use monospaced font, but in that case you will need to change the calc() formula by multiplying the --size variable by another value (which it's strictly dependent on the font-family and font-size) different than 1ch.






                  share|improve this answer































                    1














                    I think you're misinterpreting the min-width CSS property. min-width is generally used to define a minimum DOM width in a fluid layout, like:



                    input {
                    width: 30%;
                    min-width: 200px;
                    }


                    That would set the input element to a minimum width of 200 pixels. In this context, "px" stands for "pixels".



                    Now, if you're trying to check to make sure that input field contains at least one character when a user submits it, you'll need to do some form validation with JavaScript and PHP. If that is indeed what you're attempting to do, I'll edit this answer and do my best to help you out.






                    share|improve this answer
























                    • i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                      – Kerc
                      Aug 2 '10 at 23:30






                    • 1





                      @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                      – Marcel Korpel
                      Aug 2 '10 at 23:36











                    • Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                      – Kerc
                      Aug 2 '10 at 23:40











                    • Perhaps there is a php function for this, anybody knows ?

                      – Kerc
                      Aug 2 '10 at 23:43











                    • I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                      – peterjmag
                      Aug 2 '10 at 23:48



















                    1














                    I really liked Lyth's answer, but also really wanted it to:




                    1. Handle backspace and delete

                    2. Not require you to manually add an adjacent tag.

                    3. Enforce a min width.

                    4. Automatically be applied to elements with a specific class


                    I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.



                    HTML:



                    <div id='applicationHost'>
                    <div>Name: <input class='textbox-autosize' data-min-width='100' type="text" /></div>
                    <div>Email: <input class='textbox-autosize' data-min-width='100' type="email" /></div>
                    <div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
                    </div>


                    CSS:



                    #applicationHost {
                    font-family: courier;
                    white-space: pre;
                    }

                    input.textbox-autosize, span.invisible-autosize-helper {
                    padding:0;
                    font-size:12px;
                    font-family:Sans-serif;
                    white-space:pre;
                    }
                    input.textbox-autosize {
                    width: 100px; /* Initial width of textboxes */
                    }

                    /*
                    In order for the measurements to work out, your input and the invisible
                    span need to have the same styling.
                    */


                    JavaScript:



                    $('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
                    // Add an arbitary buffer of 15 pixels.
                    var whitespaceBuffer = 15;
                    var je = $(this);
                    var minWidth = parseInt(je.attr('data-min-width'));
                    var newVal = je.val();
                    var sizingSpanClass = 'invisible-autosize-helper';
                    var $span = je.siblings('span.' + sizingSpanClass).first();
                    // If this element hasn't been created yet, we'll create it now.
                    if ($span.length === 0) {
                    $span = $('<span/>', {
                    'class': sizingSpanClass,
                    'style': 'display: none;'
                    });
                    je.parent().append($span);
                    }
                    $span = je.siblings('span').first();
                    $span.text(newVal) ; // the hidden span takes
                    // the value of the input
                    $inputSize = $span.width();
                    $inputSize += whitespaceBuffer;
                    if($inputSize > minWidth)
                    je.css("width", $inputSize) ; // apply width of the span to the input
                    else
                    je.css("width", minWidth) ; // Ensure we're at the min width
                    });





                    share|improve this answer

































                      1














                      Just adding on top of other answers.



                      I noticed that nowadays in some browsers the input field has a scrollWidth. Which means:



                      this.style.width = this.scrollWidth + 'px';


                      should work nicely. tested in chrome, firefox and safari.



                      For deletion support, you can add '=0' first and then readjust.



                      this.style.width = 0; this.style.width = this.scrollWidth + 'px';





                      share|improve this answer





















                      • 3





                        Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                        – Uooo
                        Jul 2 '13 at 5:45






                      • 1





                        This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                        – Form
                        Nov 10 '18 at 19:12



















                      1














                      If you use Bootstrap, it could be done very easily:



                      <div contenteditable="true" class="form-control" style="display: inline"></div>



                      You will just need to fetch div's content and put it in a hidden input before submitting the form.






                      share|improve this answer































                        0














                        I just spend some time figuring out how to do it.

                        Actually the simplest way I found is to move input value to span just before the input, keeping input 1 symbol width. Though I can't be sure that it fit for your initial need.

                        Maybe it some extra code, but in react+flux based application it is quite natural solution.






                        share|improve this answer































                          0














                          Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.



                          I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup and blur are called.



                          Here is a working codepen. This codepen shows how this can be used with multiple input fields.



                          HTML Structure:



                          <input type="text" class="plain-field" placeholder="Full Name">
                          <span style="display: none;"></span>


                          jQuery:



                          function resizeInputs($text) {
                          var text = $text.val().replace(/s+/g, ' '),
                          placeholder = $text.attr('placeholder'),
                          span = $text.next('span');
                          span.text(placeholder);
                          var width = span.width();

                          if(text !== '') {
                          span.text(text);
                          var width = span.width();
                          }

                          $text.css('width', width + 5);
                          };


                          The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5 on the width is because without that the input gets cut off a tiny bit in the Edge Browser.



                          $('.plain-field').each(function() {
                          var $text = $(this);
                          resizeInputs($text);
                          });

                          $('.plain-field').on('keyup blur', function() {
                          var $text = $(this);
                          resizeInputs($text);
                          });

                          $('.plain-field').on('blur', function() {
                          var $text = $(this).val().replace(/s+/g, ' ');
                          $(this).val($text);
                          });


                          If this could be improved please let me know as this is the cleanest solution I could come up with.






                          share|improve this answer































                            0














                            Better is onvalue:



                            <input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                            It also involves pasting, dragging and dropping, etc.






                            share|improve this answer































                              0














                              Why not using just css?



                              <div id="wrapper">
                              <input onkeyup="keyup(event)">
                              <div id="ghost"></div>
                              </div>





                              function keyup(e) {
                              document.getElementById('ghost').innerText = e.target.value;
                              }

                              #wrapper {
                              position: relative;
                              min-width: 30px;
                              display: inline-block;
                              }

                              input {
                              position: absolute;
                              left:0;
                              right:0;
                              border:1px solid blue;
                              width: 100%;
                              }

                              #ghost {
                              color: transparent;
                              }

                              <div id="wrapper">
                              <input onkeyup="keyup(event)">
                              <div id="ghost"></div>
                              </div>





                              wrapper {
                              position: relative;
                              min-width: 30px;
                              border: 1px solid red;
                              display: inline-block;
                              }

                              input {
                              position: absolute;
                              left:0;
                              right:0;
                              width: 100%;
                              }

                              #ghost {
                              color: transparent;
                              }


                              this code was introduced by @Iain Todd to and I thought I should share it






                              share|improve this answer
























                              • It's not just css. It's just another js method. Interesting one.

                                – vatavale
                                Feb 26 '18 at 6:20



















                              0














                              This answer provides one of the most accurate methods of retrieving text width available in the browser and is more accurate than the accepted answer. It uses the canvas html5 element and unlike other answers does not add the element into the DOM and thus avoids any reflow issues caused by excessively adding elements to the DOM.



                              Read more about the Canvas element here in relation to text width.




                              NOTE: According to MDN the shorthand versions of the getPropertyValue() method such as font can be unreliable. I'd recommend getting the values singularly to improve compatibility. I only used it here for speed.







                              /**
                              * returns the width of child text of any DOM node as a float
                              */
                              function getTextWidth(el) {
                              // uses a cached canvas if available
                              var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                              var context = canvas.getContext("2d");
                              // get the full font style property
                              var font = window.getComputedStyle(el, null).getPropertyValue('font');
                              var text = el.value;
                              // set the font attr for the canvas text
                              context.font = font;
                              var textMeasurement = context.measureText(text);
                              return textMeasurement.width;
                              }

                              var input = document.getElementById('myInput');
                              // listen for any input on the input field
                              input.addEventListener('input', function(e) {
                              var width = Math.floor(getTextWidth(e.target));
                              // add 10 px to pad the input.
                              var widthInPx = (width + 10) + "px";
                              e.target.style.width = widthInPx;
                              }, false);

                              #myInput {
                              font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                              min-width: 40px;
                              }

                              <input id="myInput" />








                              share|improve this answer































                                0














                                A bullet-proof, generic way has to:




                                1. Take into account all possible styles of the measured input element

                                2. Be able to apply the measurement on any input without modifying the HTML or


                                Codepen demo






                                var getInputValueWidth = (function(){
                                // https://stackoverflow.com/a/49982135/104380
                                function copyNodeStyle(sourceNode, targetNode) {
                                var computedStyle = window.getComputedStyle(sourceNode);
                                Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                }

                                function createInputMeassureElm( inputelm ){
                                // create a dummy input element for measurements
                                var meassureElm = document.createElement('span');
                                // copy the read input's styles to the dummy input
                                copyNodeStyle(inputelm, meassureElm);

                                // set hard-coded styles needed for propper meassuring
                                meassureElm.style.width = 'auto';
                                meassureElm.style.position = 'absolute';
                                meassureElm.style.left = '-9999px';
                                meassureElm.style.top = '-9999px';
                                meassureElm.style.whiteSpace = 'pre';

                                meassureElm.textContent = inputelm.value || '';

                                // add the meassure element to the body
                                document.body.appendChild(meassureElm);

                                return meassureElm;
                                }

                                return function(){
                                return createInputMeassureElm(this).offsetWidth;
                                }
                                })();


                                // delegated event binding
                                document.body.addEventListener('input', onInputDelegate)

                                function onInputDelegate(e){
                                if( e.target.classList.contains('autoSize') )
                                e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                }

                                input{ 
                                font-size:1.3em;
                                padding:5px;
                                margin-bottom: 1em;
                                }

                                input.type2{
                                font-size: 2.5em;
                                letter-spacing: 4px;
                                font-style: italic;
                                }

                                <input class='autoSize' value="type something">
                                <br>
                                <input class='autoSize type2' value="here too">








                                share|improve this answer































                                  0














                                  Here is my 2 cents.
                                  Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.






                                  $(".answers_number").keyup(function(){
                                  $( "#number_box" ).html( $( this ).val() );
                                  $( this ).animate({
                                  width: $( "#number_box" ).width()+20
                                  }, 300, function() {
                                  });
                                  });

                                  #number_box {
                                  position: absolute;
                                  visibility: hidden;
                                  height: auto;
                                  width: auto;
                                  white-space: nowrap;
                                  padding:0 4px;
                                  /*Your font styles to match input*/
                                  font-family:Arial;
                                  font-size: 30px;
                                  }

                                  .answers_number {
                                  font-size: 30px;
                                  font-family:Arial;
                                  }

                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                  <input type="number" class="answers_number" />
                                  <div id="number_box">
                                  </div>








                                  share|improve this answer

























                                    Your Answer






                                    StackExchange.ifUsing("editor", function () {
                                    StackExchange.using("externalEditor", function () {
                                    StackExchange.using("snippets", function () {
                                    StackExchange.snippets.init();
                                    });
                                    });
                                    }, "code-snippets");

                                    StackExchange.ready(function() {
                                    var channelOptions = {
                                    tags: "".split(" "),
                                    id: "1"
                                    };
                                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                    StackExchange.using("externalEditor", function() {
                                    // Have to fire editor after snippets, if snippets enabled
                                    if (StackExchange.settings.snippets.snippetsEnabled) {
                                    StackExchange.using("snippets", function() {
                                    createEditor();
                                    });
                                    }
                                    else {
                                    createEditor();
                                    }
                                    });

                                    function createEditor() {
                                    StackExchange.prepareEditor({
                                    heartbeatType: 'answer',
                                    autoActivateHeartbeat: false,
                                    convertImagesToLinks: true,
                                    noModals: true,
                                    showLowRepImageUploadWarning: true,
                                    reputationToPostImages: 10,
                                    bindNavPrevention: true,
                                    postfix: "",
                                    imageUploader: {
                                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                    allowUrls: true
                                    },
                                    onDemand: true,
                                    discardSelector: ".discard-answer"
                                    ,immediatelyShowMarkdownHelp:true
                                    });


                                    }
                                    });














                                    draft saved

                                    draft discarded


















                                    StackExchange.ready(
                                    function () {
                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3392493%2fadjust-width-of-input-field-to-its-input%23new-answer', 'question_page');
                                    }
                                    );

                                    Post as a guest















                                    Required, but never shown

























                                    24 Answers
                                    24






                                    active

                                    oldest

                                    votes








                                    24 Answers
                                    24






                                    active

                                    oldest

                                    votes









                                    active

                                    oldest

                                    votes






                                    active

                                    oldest

                                    votes









                                    72














                                    It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:



                                    <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                    Note: this solution only works when every character is exactly 8px wide.






                                    share|improve this answer





















                                    • 22





                                      @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                      – Marcel Korpel
                                      Aug 3 '10 at 0:25






                                    • 6





                                      I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                      – Tahbaza
                                      Aug 3 '10 at 0:43






                                    • 1





                                      – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                      – Marcel Korpel
                                      Aug 3 '10 at 11:25






                                    • 2





                                      Here is a demo for those interested: jsfiddle.net/73T7S

                                      – starbeamrainbowlabs
                                      Jul 2 '13 at 6:39






                                    • 4





                                      you have forgotten the PASTE event my friend ;) you should change it to onInput

                                      – vsync
                                      Jan 27 '17 at 22:37


















                                    72














                                    It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:



                                    <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                    Note: this solution only works when every character is exactly 8px wide.






                                    share|improve this answer





















                                    • 22





                                      @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                      – Marcel Korpel
                                      Aug 3 '10 at 0:25






                                    • 6





                                      I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                      – Tahbaza
                                      Aug 3 '10 at 0:43






                                    • 1





                                      – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                      – Marcel Korpel
                                      Aug 3 '10 at 11:25






                                    • 2





                                      Here is a demo for those interested: jsfiddle.net/73T7S

                                      – starbeamrainbowlabs
                                      Jul 2 '13 at 6:39






                                    • 4





                                      you have forgotten the PASTE event my friend ;) you should change it to onInput

                                      – vsync
                                      Jan 27 '17 at 22:37
















                                    72












                                    72








                                    72







                                    It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:



                                    <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                    Note: this solution only works when every character is exactly 8px wide.






                                    share|improve this answer















                                    It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:



                                    <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                    Note: this solution only works when every character is exactly 8px wide.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Aug 16 '17 at 15:56









                                    Chris Happy

                                    4,58811033




                                    4,58811033










                                    answered Aug 2 '10 at 23:45









                                    TahbazaTahbaza

                                    7,77712138




                                    7,77712138








                                    • 22





                                      @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                      – Marcel Korpel
                                      Aug 3 '10 at 0:25






                                    • 6





                                      I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                      – Tahbaza
                                      Aug 3 '10 at 0:43






                                    • 1





                                      – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                      – Marcel Korpel
                                      Aug 3 '10 at 11:25






                                    • 2





                                      Here is a demo for those interested: jsfiddle.net/73T7S

                                      – starbeamrainbowlabs
                                      Jul 2 '13 at 6:39






                                    • 4





                                      you have forgotten the PASTE event my friend ;) you should change it to onInput

                                      – vsync
                                      Jan 27 '17 at 22:37
















                                    • 22





                                      @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                      – Marcel Korpel
                                      Aug 3 '10 at 0:25






                                    • 6





                                      I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                      – Tahbaza
                                      Aug 3 '10 at 0:43






                                    • 1





                                      – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                      – Marcel Korpel
                                      Aug 3 '10 at 11:25






                                    • 2





                                      Here is a demo for those interested: jsfiddle.net/73T7S

                                      – starbeamrainbowlabs
                                      Jul 2 '13 at 6:39






                                    • 4





                                      you have forgotten the PASTE event my friend ;) you should change it to onInput

                                      – vsync
                                      Jan 27 '17 at 22:37










                                    22




                                    22





                                    @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                    – Marcel Korpel
                                    Aug 3 '10 at 0:25





                                    @Kerc & Tahbaza: yes, but this will only work if the width of every character is exactly 8 pixels.

                                    – Marcel Korpel
                                    Aug 3 '10 at 0:25




                                    6




                                    6





                                    I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                    – Tahbaza
                                    Aug 3 '10 at 0:43





                                    I agree, Marcel (and the posted code is not something I can see a use for really) but it exhibits the desired behavior. Do you know how to calculate the actual width of rendered text taking into account font, size, weight, kerning, etc.? If so, please share as I would find that bit of code useful on occasion.

                                    – Tahbaza
                                    Aug 3 '10 at 0:43




                                    1




                                    1





                                    – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                    – Marcel Korpel
                                    Aug 3 '10 at 11:25





                                    – I already thought that it was only an example. It's not that difficult to calculate the width of the input, though. Have a look at my answer.

                                    – Marcel Korpel
                                    Aug 3 '10 at 11:25




                                    2




                                    2





                                    Here is a demo for those interested: jsfiddle.net/73T7S

                                    – starbeamrainbowlabs
                                    Jul 2 '13 at 6:39





                                    Here is a demo for those interested: jsfiddle.net/73T7S

                                    – starbeamrainbowlabs
                                    Jul 2 '13 at 6:39




                                    4




                                    4





                                    you have forgotten the PASTE event my friend ;) you should change it to onInput

                                    – vsync
                                    Jan 27 '17 at 22:37







                                    you have forgotten the PASTE event my friend ;) you should change it to onInput

                                    – vsync
                                    Jan 27 '17 at 22:37















                                    58














                                    To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.



                                    I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.



                                    BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.



                                    <!DOCTYPE html>
                                    <html>
                                    <head>
                                    <meta charset="utf-8">
                                    <title>Get/set width of &lt;input&gt;</title>
                                    <style>
                                    body {
                                    background: #666;
                                    }

                                    .input-element {
                                    border: 0;
                                    padding: 2px;
                                    background: #fff;
                                    font: 12pt sans-serif;
                                    }

                                    .tmp-element {
                                    visibility: hidden;
                                    white-space: pre;
                                    }
                                    </style>
                                    </head>
                                    <body>
                                    <input id="theInput" type="text" class="input-element" value="1">
                                    <script>
                                    var inputEl = document.getElementById("theInput");

                                    function getWidthOfInput() {
                                    var tmp = document.createElement("span");
                                    tmp.className = "input-element tmp-element";
                                    tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                                    document.body.appendChild(tmp);
                                    var theWidth = tmp.getBoundingClientRect().width;
                                    document.body.removeChild(tmp);
                                    return theWidth;
                                    }

                                    function adjustWidthOfInput() {
                                    inputEl.style.width = getWidthOfInput() + "px";
                                    }

                                    adjustWidthOfInput();
                                    inputEl.onkeyup = adjustWidthOfInput;
                                    </script>
                                    </body>
                                    </html>





                                    share|improve this answer


























                                    • I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                      – Nathan
                                      Sep 18 '12 at 21:14








                                    • 9





                                      You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                      – Timo Kähkönen
                                      Feb 28 '13 at 23:36











                                    • @Timo: You're right, thanks.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:27






                                    • 2





                                      tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                      – lisak
                                      Jan 6 '15 at 16:18











                                    • @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                      – Marcel Korpel
                                      Jan 6 '15 at 16:25
















                                    58














                                    To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.



                                    I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.



                                    BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.



                                    <!DOCTYPE html>
                                    <html>
                                    <head>
                                    <meta charset="utf-8">
                                    <title>Get/set width of &lt;input&gt;</title>
                                    <style>
                                    body {
                                    background: #666;
                                    }

                                    .input-element {
                                    border: 0;
                                    padding: 2px;
                                    background: #fff;
                                    font: 12pt sans-serif;
                                    }

                                    .tmp-element {
                                    visibility: hidden;
                                    white-space: pre;
                                    }
                                    </style>
                                    </head>
                                    <body>
                                    <input id="theInput" type="text" class="input-element" value="1">
                                    <script>
                                    var inputEl = document.getElementById("theInput");

                                    function getWidthOfInput() {
                                    var tmp = document.createElement("span");
                                    tmp.className = "input-element tmp-element";
                                    tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                                    document.body.appendChild(tmp);
                                    var theWidth = tmp.getBoundingClientRect().width;
                                    document.body.removeChild(tmp);
                                    return theWidth;
                                    }

                                    function adjustWidthOfInput() {
                                    inputEl.style.width = getWidthOfInput() + "px";
                                    }

                                    adjustWidthOfInput();
                                    inputEl.onkeyup = adjustWidthOfInput;
                                    </script>
                                    </body>
                                    </html>





                                    share|improve this answer


























                                    • I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                      – Nathan
                                      Sep 18 '12 at 21:14








                                    • 9





                                      You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                      – Timo Kähkönen
                                      Feb 28 '13 at 23:36











                                    • @Timo: You're right, thanks.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:27






                                    • 2





                                      tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                      – lisak
                                      Jan 6 '15 at 16:18











                                    • @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                      – Marcel Korpel
                                      Jan 6 '15 at 16:25














                                    58












                                    58








                                    58







                                    To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.



                                    I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.



                                    BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.



                                    <!DOCTYPE html>
                                    <html>
                                    <head>
                                    <meta charset="utf-8">
                                    <title>Get/set width of &lt;input&gt;</title>
                                    <style>
                                    body {
                                    background: #666;
                                    }

                                    .input-element {
                                    border: 0;
                                    padding: 2px;
                                    background: #fff;
                                    font: 12pt sans-serif;
                                    }

                                    .tmp-element {
                                    visibility: hidden;
                                    white-space: pre;
                                    }
                                    </style>
                                    </head>
                                    <body>
                                    <input id="theInput" type="text" class="input-element" value="1">
                                    <script>
                                    var inputEl = document.getElementById("theInput");

                                    function getWidthOfInput() {
                                    var tmp = document.createElement("span");
                                    tmp.className = "input-element tmp-element";
                                    tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                                    document.body.appendChild(tmp);
                                    var theWidth = tmp.getBoundingClientRect().width;
                                    document.body.removeChild(tmp);
                                    return theWidth;
                                    }

                                    function adjustWidthOfInput() {
                                    inputEl.style.width = getWidthOfInput() + "px";
                                    }

                                    adjustWidthOfInput();
                                    inputEl.onkeyup = adjustWidthOfInput;
                                    </script>
                                    </body>
                                    </html>





                                    share|improve this answer















                                    To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.



                                    I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.



                                    BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.



                                    <!DOCTYPE html>
                                    <html>
                                    <head>
                                    <meta charset="utf-8">
                                    <title>Get/set width of &lt;input&gt;</title>
                                    <style>
                                    body {
                                    background: #666;
                                    }

                                    .input-element {
                                    border: 0;
                                    padding: 2px;
                                    background: #fff;
                                    font: 12pt sans-serif;
                                    }

                                    .tmp-element {
                                    visibility: hidden;
                                    white-space: pre;
                                    }
                                    </style>
                                    </head>
                                    <body>
                                    <input id="theInput" type="text" class="input-element" value="1">
                                    <script>
                                    var inputEl = document.getElementById("theInput");

                                    function getWidthOfInput() {
                                    var tmp = document.createElement("span");
                                    tmp.className = "input-element tmp-element";
                                    tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                                    document.body.appendChild(tmp);
                                    var theWidth = tmp.getBoundingClientRect().width;
                                    document.body.removeChild(tmp);
                                    return theWidth;
                                    }

                                    function adjustWidthOfInput() {
                                    inputEl.style.width = getWidthOfInput() + "px";
                                    }

                                    adjustWidthOfInput();
                                    inputEl.onkeyup = adjustWidthOfInput;
                                    </script>
                                    </body>
                                    </html>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jan 6 '15 at 16:24

























                                    answered Aug 3 '10 at 11:24









                                    Marcel KorpelMarcel Korpel

                                    19.2k45273




                                    19.2k45273













                                    • I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                      – Nathan
                                      Sep 18 '12 at 21:14








                                    • 9





                                      You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                      – Timo Kähkönen
                                      Feb 28 '13 at 23:36











                                    • @Timo: You're right, thanks.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:27






                                    • 2





                                      tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                      – lisak
                                      Jan 6 '15 at 16:18











                                    • @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                      – Marcel Korpel
                                      Jan 6 '15 at 16:25



















                                    • I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                      – Nathan
                                      Sep 18 '12 at 21:14








                                    • 9





                                      You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                      – Timo Kähkönen
                                      Feb 28 '13 at 23:36











                                    • @Timo: You're right, thanks.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:27






                                    • 2





                                      tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                      – lisak
                                      Jan 6 '15 at 16:18











                                    • @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                      – Marcel Korpel
                                      Jan 6 '15 at 16:25

















                                    I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                    – Nathan
                                    Sep 18 '12 at 21:14







                                    I liked your answer and even implemented it using jQuery/Underscore: gist.github.com/3745941. However, I could make certain assumptions: (1) the width of any character is no more than 14px, (2) it's acceptable to have the input element extend 14px past the value of the element. I have this attached to a keydown event and it's working great!

                                    – Nathan
                                    Sep 18 '12 at 21:14






                                    9




                                    9





                                    You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                    – Timo Kähkönen
                                    Feb 28 '13 at 23:36





                                    You should add white-space: pre; into css this way: .tmp-element{ visibility: hidden; white-space: pre;}. Otherwise white-spaces are combined and the width calculation fails. <input> and <span> behaves differently regarding to white-space handling, <input> retains white-spaces and <span> combines sequential white-spaces into one if white-space: pre; is not added.

                                    – Timo Kähkönen
                                    Feb 28 '13 at 23:36













                                    @Timo: You're right, thanks.

                                    – Marcel Korpel
                                    Mar 1 '13 at 12:27





                                    @Timo: You're right, thanks.

                                    – Marcel Korpel
                                    Mar 1 '13 at 12:27




                                    2




                                    2





                                    tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                    – lisak
                                    Jan 6 '15 at 16:18





                                    tmp.getBoundingClientRect().width is better than tmp.scrollWidth, because that sometimes returns 0

                                    – lisak
                                    Jan 6 '15 at 16:18













                                    @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                    – Marcel Korpel
                                    Jan 6 '15 at 16:25





                                    @lisak Thanks, I adjusted my answer, but there are already better answers here.

                                    – Marcel Korpel
                                    Jan 6 '15 at 16:25











                                    44














                                    In modern browser versions, CSS unit ch is also available. To my understanding, it is font-independent unit, where 1ch equals to width of character 0 (zero) in any given font.



                                    Thus, something as simple as following could be used as resize function:






                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>





                                    That example would resize "elem" to length of the value + 2 characters extra.






                                    share|improve this answer





















                                    • 7





                                      I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                      – Husky
                                      Jun 9 '17 at 19:09











                                    • I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                      – Lonnie Best
                                      May 13 '18 at 4:02






                                    • 4





                                      This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                      – vsync
                                      May 16 '18 at 10:25











                                    • Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                      – Jilles van Gurp
                                      2 days ago
















                                    44














                                    In modern browser versions, CSS unit ch is also available. To my understanding, it is font-independent unit, where 1ch equals to width of character 0 (zero) in any given font.



                                    Thus, something as simple as following could be used as resize function:






                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>





                                    That example would resize "elem" to length of the value + 2 characters extra.






                                    share|improve this answer





















                                    • 7





                                      I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                      – Husky
                                      Jun 9 '17 at 19:09











                                    • I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                      – Lonnie Best
                                      May 13 '18 at 4:02






                                    • 4





                                      This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                      – vsync
                                      May 16 '18 at 10:25











                                    • Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                      – Jilles van Gurp
                                      2 days ago














                                    44












                                    44








                                    44







                                    In modern browser versions, CSS unit ch is also available. To my understanding, it is font-independent unit, where 1ch equals to width of character 0 (zero) in any given font.



                                    Thus, something as simple as following could be used as resize function:






                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>





                                    That example would resize "elem" to length of the value + 2 characters extra.






                                    share|improve this answer















                                    In modern browser versions, CSS unit ch is also available. To my understanding, it is font-independent unit, where 1ch equals to width of character 0 (zero) in any given font.



                                    Thus, something as simple as following could be used as resize function:






                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>





                                    That example would resize "elem" to length of the value + 2 characters extra.






                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>





                                    var input = document.querySelector('input'); // get the input element
                                    input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
                                    resizeInput.call(input); // immediately call the function

                                    function resizeInput() {
                                    this.style.width = this.value.length + "ch";
                                    }

                                    input{ font-size:1.3em; padding:.5em; }

                                    <input>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 16 '18 at 10:23









                                    vsync

                                    46.6k36159220




                                    46.6k36159220










                                    answered Apr 19 '17 at 7:12









                                    Jani JalkalaJani Jalkala

                                    54943




                                    54943








                                    • 7





                                      I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                      – Husky
                                      Jun 9 '17 at 19:09











                                    • I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                      – Lonnie Best
                                      May 13 '18 at 4:02






                                    • 4





                                      This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                      – vsync
                                      May 16 '18 at 10:25











                                    • Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                      – Jilles van Gurp
                                      2 days ago














                                    • 7





                                      I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                      – Husky
                                      Jun 9 '17 at 19:09











                                    • I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                      – Lonnie Best
                                      May 13 '18 at 4:02






                                    • 4





                                      This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                      – vsync
                                      May 16 '18 at 10:25











                                    • Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                      – Jilles van Gurp
                                      2 days ago








                                    7




                                    7





                                    I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                    – Husky
                                    Jun 9 '17 at 19:09





                                    I'm surprised this comment isn't voted up higher, because it is a great solution and about 95% (1) of browsers support this.

                                    – Husky
                                    Jun 9 '17 at 19:09













                                    I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                    – Lonnie Best
                                    May 13 '18 at 4:02





                                    I love this answer. ch is great; I wonder what other units I'm late in discovering. Thanks.

                                    – Lonnie Best
                                    May 13 '18 at 4:02




                                    4




                                    4





                                    This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                    – vsync
                                    May 16 '18 at 10:25





                                    This is not a good answer at all, since the measurement is not accurate and does not take into account styles that might occur on the input element, such as font-style, letter-spacing and so on. I've edited the answer with a live demo.

                                    – vsync
                                    May 16 '18 at 10:25













                                    Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                    – Jilles van Gurp
                                    2 days ago





                                    Works great if you use a monospaced font. With other fonts your mileage may vary as it uses the character width of the 0 character apparently.

                                    – Jilles van Gurp
                                    2 days ago











                                    25














                                    Here's a modification of Lyth's answer that takes into account:




                                    • Deletion

                                    • Initialisation

                                    • Placeholders


                                    It also allows for any number of input fields! To see it in action: http://jsfiddle.net/4Qsa8/



                                    Script:



                                    $(document).ready(function () {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function (e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function (e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function () {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });


                                    Style:



                                    .resizing-input input, .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }


                                    HTML:



                                    <div class="resizing-input">
                                    <input type="text" placeholder="placeholder"/>
                                    <span style="display:none"></span>
                                    </div>





                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>








                                    share|improve this answer


























                                    • Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                      – Maxence
                                      Jan 19 '18 at 21:13






                                    • 1





                                      @Maxence listening to the change or input event would suffice

                                      – yarwest
                                      Aug 6 '18 at 14:10











                                    • I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                      – jayt
                                      Aug 21 '18 at 9:59











                                    • Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                      – Maxence
                                      Oct 12 '18 at 15:20
















                                    25














                                    Here's a modification of Lyth's answer that takes into account:




                                    • Deletion

                                    • Initialisation

                                    • Placeholders


                                    It also allows for any number of input fields! To see it in action: http://jsfiddle.net/4Qsa8/



                                    Script:



                                    $(document).ready(function () {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function (e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function (e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function () {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });


                                    Style:



                                    .resizing-input input, .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }


                                    HTML:



                                    <div class="resizing-input">
                                    <input type="text" placeholder="placeholder"/>
                                    <span style="display:none"></span>
                                    </div>





                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>








                                    share|improve this answer


























                                    • Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                      – Maxence
                                      Jan 19 '18 at 21:13






                                    • 1





                                      @Maxence listening to the change or input event would suffice

                                      – yarwest
                                      Aug 6 '18 at 14:10











                                    • I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                      – jayt
                                      Aug 21 '18 at 9:59











                                    • Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                      – Maxence
                                      Oct 12 '18 at 15:20














                                    25












                                    25








                                    25







                                    Here's a modification of Lyth's answer that takes into account:




                                    • Deletion

                                    • Initialisation

                                    • Placeholders


                                    It also allows for any number of input fields! To see it in action: http://jsfiddle.net/4Qsa8/



                                    Script:



                                    $(document).ready(function () {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function (e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function (e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function () {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });


                                    Style:



                                    .resizing-input input, .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }


                                    HTML:



                                    <div class="resizing-input">
                                    <input type="text" placeholder="placeholder"/>
                                    <span style="display:none"></span>
                                    </div>





                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>








                                    share|improve this answer















                                    Here's a modification of Lyth's answer that takes into account:




                                    • Deletion

                                    • Initialisation

                                    • Placeholders


                                    It also allows for any number of input fields! To see it in action: http://jsfiddle.net/4Qsa8/



                                    Script:



                                    $(document).ready(function () {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function (e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function (e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function () {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });


                                    Style:



                                    .resizing-input input, .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }


                                    HTML:



                                    <div class="resizing-input">
                                    <input type="text" placeholder="placeholder"/>
                                    <span style="display:none"></span>
                                    </div>





                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>








                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>





                                    $(document).ready(function() {
                                    var $inputs = $('.resizing-input');

                                    // Resize based on text if text.length > 0
                                    // Otherwise resize based on the placeholder
                                    function resizeForText(text) {
                                    var $this = $(this);
                                    if (!text.trim()) {
                                    text = $this.attr('placeholder').trim();
                                    }
                                    var $span = $this.parent().find('span');
                                    $span.text(text);
                                    var $inputSize = $span.width();
                                    $this.css("width", $inputSize);
                                    }

                                    $inputs.find('input').keypress(function(e) {
                                    if (e.which && e.charCode) {
                                    var c = String.fromCharCode(e.keyCode | e.charCode);
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val() + c);
                                    }
                                    });

                                    // Backspace event only fires for keyup
                                    $inputs.find('input').keyup(function(e) {
                                    if (e.keyCode === 8 || e.keyCode === 46) {
                                    resizeForText.call($(this), $(this).val());
                                    }
                                    });

                                    $inputs.find('input').each(function() {
                                    var $this = $(this);
                                    resizeForText.call($this, $this.val())
                                    });
                                    });

                                    .resizing-input input,
                                    .resizing-input span {
                                    font-size: 12px;
                                    font-family: Sans-serif;
                                    white-space: pre;
                                    padding: 5px;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
                                    <div class="resizing-input">
                                    First:
                                    <input type="text" placeholder="placeholder" />
                                    <span style="display:none"></span>
                                    </div>
                                    <br>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Aug 27 '15 at 11:57









                                    Sarfaraaz

                                    379416




                                    379416










                                    answered Jun 17 '14 at 9:18









                                    MichaelMichael

                                    1,62111831




                                    1,62111831













                                    • Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                      – Maxence
                                      Jan 19 '18 at 21:13






                                    • 1





                                      @Maxence listening to the change or input event would suffice

                                      – yarwest
                                      Aug 6 '18 at 14:10











                                    • I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                      – jayt
                                      Aug 21 '18 at 9:59











                                    • Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                      – Maxence
                                      Oct 12 '18 at 15:20



















                                    • Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                      – Maxence
                                      Jan 19 '18 at 21:13






                                    • 1





                                      @Maxence listening to the change or input event would suffice

                                      – yarwest
                                      Aug 6 '18 at 14:10











                                    • I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                      – jayt
                                      Aug 21 '18 at 9:59











                                    • Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                      – Maxence
                                      Oct 12 '18 at 15:20

















                                    Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                    – Maxence
                                    Jan 19 '18 at 21:13





                                    Hi @Michael. Your code works great but I have a problem. One of my field is a Google place autocmplete field. And when I pick the right address from a dropped down menu, the width of the input field is not changed according the length of the address chosen. Is there a simple fix for it ?

                                    – Maxence
                                    Jan 19 '18 at 21:13




                                    1




                                    1





                                    @Maxence listening to the change or input event would suffice

                                    – yarwest
                                    Aug 6 '18 at 14:10





                                    @Maxence listening to the change or input event would suffice

                                    – yarwest
                                    Aug 6 '18 at 14:10













                                    I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                    – jayt
                                    Aug 21 '18 at 9:59





                                    I had issues with the span's display:none styling since it registered the span as having 0 width. Better to use absolute positioning with visibility:hidden for the span.

                                    – jayt
                                    Aug 21 '18 at 9:59













                                    Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                    – Maxence
                                    Oct 12 '18 at 15:20





                                    Hi @yarwest , thanks for the tip. By any chance would you know how to tweak the original script with this setup ? (my knowledge in Js/jquery is very very limited)

                                    – Maxence
                                    Oct 12 '18 at 15:20











                                    15














                                    FOR A NICER LOOK&FEEL



                                    You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)



                                    Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/



                                    Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.






                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>








                                    share|improve this answer





















                                    • 1





                                      Looks nice, but it doesn't take Backspace and Delete into account.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:31











                                    • Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                      – Lyth
                                      Mar 3 '13 at 14:21













                                    • If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                      – Frinsh
                                      May 6 '15 at 12:08













                                    • I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                      – vsync
                                      May 16 '18 at 11:04
















                                    15














                                    FOR A NICER LOOK&FEEL



                                    You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)



                                    Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/



                                    Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.






                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>








                                    share|improve this answer





















                                    • 1





                                      Looks nice, but it doesn't take Backspace and Delete into account.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:31











                                    • Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                      – Lyth
                                      Mar 3 '13 at 14:21













                                    • If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                      – Frinsh
                                      May 6 '15 at 12:08













                                    • I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                      – vsync
                                      May 16 '18 at 11:04














                                    15












                                    15








                                    15







                                    FOR A NICER LOOK&FEEL



                                    You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)



                                    Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/



                                    Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.






                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>








                                    share|improve this answer















                                    FOR A NICER LOOK&FEEL



                                    You should use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence you can calculate what your width will be. Why? Because it will look a lot more sexy :)



                                    Here is a jsfiddle that results in a nice behaviour compared to solutions using the keyup event : http://jsfiddle.net/G4FKW/3/



                                    Below is a vanilla JS which listens to the input event of an <input> element and sets a span sibling to have the same text value in order to measure it.






                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>








                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>





                                    document.querySelector('input').addEventListener('input', onInput)

                                    function onInput(){
                                    var spanElm = this.nextElementSibling;
                                    spanElm.textContent = this.value; // the hidden span takes the value of the input;
                                    this.style.width = spanElm.offsetWidth + 'px'; // apply width of the span to the input
                                    };

                                    /* it's important the input and its span have same styling */
                                    input, .measure {
                                    padding: 5px;
                                    font-size: 2.3rem;
                                    font-family: Sans-serif;
                                    white-space: pre; /* white-spaces will work effectively */
                                    }

                                    .measure{
                                    position: absolute;
                                    left: -9999px;
                                    top: -9999px;
                                    }

                                    <input type="text" />
                                    <span class='measure'></span>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 16 '18 at 11:02









                                    vsync

                                    46.6k36159220




                                    46.6k36159220










                                    answered Feb 13 '13 at 14:29









                                    LythLyth

                                    7762925




                                    7762925








                                    • 1





                                      Looks nice, but it doesn't take Backspace and Delete into account.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:31











                                    • Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                      – Lyth
                                      Mar 3 '13 at 14:21













                                    • If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                      – Frinsh
                                      May 6 '15 at 12:08













                                    • I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                      – vsync
                                      May 16 '18 at 11:04














                                    • 1





                                      Looks nice, but it doesn't take Backspace and Delete into account.

                                      – Marcel Korpel
                                      Mar 1 '13 at 12:31











                                    • Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                      – Lyth
                                      Mar 3 '13 at 14:21













                                    • If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                      – Frinsh
                                      May 6 '15 at 12:08













                                    • I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                      – vsync
                                      May 16 '18 at 11:04








                                    1




                                    1





                                    Looks nice, but it doesn't take Backspace and Delete into account.

                                    – Marcel Korpel
                                    Mar 1 '13 at 12:31





                                    Looks nice, but it doesn't take Backspace and Delete into account.

                                    – Marcel Korpel
                                    Mar 1 '13 at 12:31













                                    Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                    – Lyth
                                    Mar 3 '13 at 14:21







                                    Yes, for this you need keydown event. You can add specific handling for backspace and delete by doing so (e.which === 46 for delete, e.which === 8 for backspace). But you still need keypress event to have access to e.charCode for the rest.

                                    – Lyth
                                    Mar 3 '13 at 14:21















                                    If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                    – Frinsh
                                    May 6 '15 at 12:08







                                    If you're not supporting IE8 you can use the oninput event instead of checking e.which: developer.mozilla.org/en-US/docs/Web/Events/input

                                    – Frinsh
                                    May 6 '15 at 12:08















                                    I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                    – vsync
                                    May 16 '18 at 11:04





                                    I've edited your answer to eliminate jQuery and use only vanilla JS. mind that this solution is far from optimal because you want a generic solution that doesn't involve in manually coding a span and css for it.

                                    – vsync
                                    May 16 '18 at 11:04











                                    11














                                    Here is a solution without monospaced font needed, with only very small piece code of javascript, do not need calculate computed styles, and, even support ime, support rtl texts.






                                    // copy the text from input to the span
                                    $(function () {
                                    $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                    });

                                        * {
                                    box-sizing: border-box;
                                    }

                                    .container {
                                    display: inline-block;
                                    position: relative;
                                    }

                                    .input,
                                    .text {
                                    margin: 0;
                                    padding: 2px 10px;
                                    font-size: 24px;
                                    line-height: 32px;
                                    border: 1px solid #ccc;
                                    box-radius: 3px;
                                    height: 36px;
                                    font: 20px/20px sans-serif;
                                    /* font: they should use same font; */
                                    }

                                    .text {
                                    padding-right: 20px;
                                    display: inline-block;
                                    visibility: hidden;
                                    white-space: pre;
                                    }

                                    .input {
                                    position: absolute;
                                    top: 0;
                                    left: 0;
                                    right: 0;
                                    bottom: 0;
                                    width: 100%;
                                    }

                                    <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                    <div class="container">
                                    <span class="text">
                                    some text
                                    </span>
                                    <input class="input" value="some text" />
                                    </div>





                                    Use the span.text to fit width of text, and let the input have same size with it by position: absolute to the container. Copy value of input to the span every time it changed (you may change this piece of code to vanilla js easily). So the input will just "fit" the size of its content.






                                    share|improve this answer






























                                      11














                                      Here is a solution without monospaced font needed, with only very small piece code of javascript, do not need calculate computed styles, and, even support ime, support rtl texts.






                                      // copy the text from input to the span
                                      $(function () {
                                      $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                      });

                                          * {
                                      box-sizing: border-box;
                                      }

                                      .container {
                                      display: inline-block;
                                      position: relative;
                                      }

                                      .input,
                                      .text {
                                      margin: 0;
                                      padding: 2px 10px;
                                      font-size: 24px;
                                      line-height: 32px;
                                      border: 1px solid #ccc;
                                      box-radius: 3px;
                                      height: 36px;
                                      font: 20px/20px sans-serif;
                                      /* font: they should use same font; */
                                      }

                                      .text {
                                      padding-right: 20px;
                                      display: inline-block;
                                      visibility: hidden;
                                      white-space: pre;
                                      }

                                      .input {
                                      position: absolute;
                                      top: 0;
                                      left: 0;
                                      right: 0;
                                      bottom: 0;
                                      width: 100%;
                                      }

                                      <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                      <div class="container">
                                      <span class="text">
                                      some text
                                      </span>
                                      <input class="input" value="some text" />
                                      </div>





                                      Use the span.text to fit width of text, and let the input have same size with it by position: absolute to the container. Copy value of input to the span every time it changed (you may change this piece of code to vanilla js easily). So the input will just "fit" the size of its content.






                                      share|improve this answer




























                                        11












                                        11








                                        11







                                        Here is a solution without monospaced font needed, with only very small piece code of javascript, do not need calculate computed styles, and, even support ime, support rtl texts.






                                        // copy the text from input to the span
                                        $(function () {
                                        $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                        });

                                            * {
                                        box-sizing: border-box;
                                        }

                                        .container {
                                        display: inline-block;
                                        position: relative;
                                        }

                                        .input,
                                        .text {
                                        margin: 0;
                                        padding: 2px 10px;
                                        font-size: 24px;
                                        line-height: 32px;
                                        border: 1px solid #ccc;
                                        box-radius: 3px;
                                        height: 36px;
                                        font: 20px/20px sans-serif;
                                        /* font: they should use same font; */
                                        }

                                        .text {
                                        padding-right: 20px;
                                        display: inline-block;
                                        visibility: hidden;
                                        white-space: pre;
                                        }

                                        .input {
                                        position: absolute;
                                        top: 0;
                                        left: 0;
                                        right: 0;
                                        bottom: 0;
                                        width: 100%;
                                        }

                                        <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                        <div class="container">
                                        <span class="text">
                                        some text
                                        </span>
                                        <input class="input" value="some text" />
                                        </div>





                                        Use the span.text to fit width of text, and let the input have same size with it by position: absolute to the container. Copy value of input to the span every time it changed (you may change this piece of code to vanilla js easily). So the input will just "fit" the size of its content.






                                        share|improve this answer















                                        Here is a solution without monospaced font needed, with only very small piece code of javascript, do not need calculate computed styles, and, even support ime, support rtl texts.






                                        // copy the text from input to the span
                                        $(function () {
                                        $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                        });

                                            * {
                                        box-sizing: border-box;
                                        }

                                        .container {
                                        display: inline-block;
                                        position: relative;
                                        }

                                        .input,
                                        .text {
                                        margin: 0;
                                        padding: 2px 10px;
                                        font-size: 24px;
                                        line-height: 32px;
                                        border: 1px solid #ccc;
                                        box-radius: 3px;
                                        height: 36px;
                                        font: 20px/20px sans-serif;
                                        /* font: they should use same font; */
                                        }

                                        .text {
                                        padding-right: 20px;
                                        display: inline-block;
                                        visibility: hidden;
                                        white-space: pre;
                                        }

                                        .input {
                                        position: absolute;
                                        top: 0;
                                        left: 0;
                                        right: 0;
                                        bottom: 0;
                                        width: 100%;
                                        }

                                        <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                        <div class="container">
                                        <span class="text">
                                        some text
                                        </span>
                                        <input class="input" value="some text" />
                                        </div>





                                        Use the span.text to fit width of text, and let the input have same size with it by position: absolute to the container. Copy value of input to the span every time it changed (you may change this piece of code to vanilla js easily). So the input will just "fit" the size of its content.






                                        // copy the text from input to the span
                                        $(function () {
                                        $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                        });

                                            * {
                                        box-sizing: border-box;
                                        }

                                        .container {
                                        display: inline-block;
                                        position: relative;
                                        }

                                        .input,
                                        .text {
                                        margin: 0;
                                        padding: 2px 10px;
                                        font-size: 24px;
                                        line-height: 32px;
                                        border: 1px solid #ccc;
                                        box-radius: 3px;
                                        height: 36px;
                                        font: 20px/20px sans-serif;
                                        /* font: they should use same font; */
                                        }

                                        .text {
                                        padding-right: 20px;
                                        display: inline-block;
                                        visibility: hidden;
                                        white-space: pre;
                                        }

                                        .input {
                                        position: absolute;
                                        top: 0;
                                        left: 0;
                                        right: 0;
                                        bottom: 0;
                                        width: 100%;
                                        }

                                        <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                        <div class="container">
                                        <span class="text">
                                        some text
                                        </span>
                                        <input class="input" value="some text" />
                                        </div>





                                        // copy the text from input to the span
                                        $(function () {
                                        $('.input').on('input', function () { $('.text').text($('.input').val()); });
                                        });

                                            * {
                                        box-sizing: border-box;
                                        }

                                        .container {
                                        display: inline-block;
                                        position: relative;
                                        }

                                        .input,
                                        .text {
                                        margin: 0;
                                        padding: 2px 10px;
                                        font-size: 24px;
                                        line-height: 32px;
                                        border: 1px solid #ccc;
                                        box-radius: 3px;
                                        height: 36px;
                                        font: 20px/20px sans-serif;
                                        /* font: they should use same font; */
                                        }

                                        .text {
                                        padding-right: 20px;
                                        display: inline-block;
                                        visibility: hidden;
                                        white-space: pre;
                                        }

                                        .input {
                                        position: absolute;
                                        top: 0;
                                        left: 0;
                                        right: 0;
                                        bottom: 0;
                                        width: 100%;
                                        }

                                        <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>

                                        <div class="container">
                                        <span class="text">
                                        some text
                                        </span>
                                        <input class="input" value="some text" />
                                        </div>






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 6 '18 at 7:03

























                                        answered Dec 30 '16 at 2:47









                                        tshtsh

                                        1,4151427




                                        1,4151427























                                            8














                                            You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.



                                            An input could dynamically adjust it's size by listening for key events.



                                            For example



                                            $("input[type='text']").bind('keyup', function () {
                                            $(this).attr("size", $(this).val().length );
                                            });


                                            JsFiddle here






                                            share|improve this answer




























                                              8














                                              You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.



                                              An input could dynamically adjust it's size by listening for key events.



                                              For example



                                              $("input[type='text']").bind('keyup', function () {
                                              $(this).attr("size", $(this).val().length );
                                              });


                                              JsFiddle here






                                              share|improve this answer


























                                                8












                                                8








                                                8







                                                You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.



                                                An input could dynamically adjust it's size by listening for key events.



                                                For example



                                                $("input[type='text']").bind('keyup', function () {
                                                $(this).attr("size", $(this).val().length );
                                                });


                                                JsFiddle here






                                                share|improve this answer













                                                You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.



                                                An input could dynamically adjust it's size by listening for key events.



                                                For example



                                                $("input[type='text']").bind('keyup', function () {
                                                $(this).attr("size", $(this).val().length );
                                                });


                                                JsFiddle here







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Feb 13 '14 at 23:31









                                                brendanbrendan

                                                4,99332024




                                                4,99332024























                                                    7














                                                    You could do something like this



                                                    // HTML
                                                    <input id="input" type="text" style="width:3px" />
                                                    // jQuery
                                                    $(function(){
                                                    $('#input').keyup(function(){
                                                    $('<span id="width">').append( $(this).val() ).appendTo('body');
                                                    $(this).width( $('#width').width() + 2 );
                                                    $('#width').remove();
                                                    });
                                                    });









                                                    share|improve this answer
























                                                    • Only if body > span has the exact same styling as #input...

                                                      – Trevor Burnham
                                                      Jun 15 '12 at 22:31











                                                    • If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                      – Lyth
                                                      Feb 13 '13 at 13:35
















                                                    7














                                                    You could do something like this



                                                    // HTML
                                                    <input id="input" type="text" style="width:3px" />
                                                    // jQuery
                                                    $(function(){
                                                    $('#input').keyup(function(){
                                                    $('<span id="width">').append( $(this).val() ).appendTo('body');
                                                    $(this).width( $('#width').width() + 2 );
                                                    $('#width').remove();
                                                    });
                                                    });









                                                    share|improve this answer
























                                                    • Only if body > span has the exact same styling as #input...

                                                      – Trevor Burnham
                                                      Jun 15 '12 at 22:31











                                                    • If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                      – Lyth
                                                      Feb 13 '13 at 13:35














                                                    7












                                                    7








                                                    7







                                                    You could do something like this



                                                    // HTML
                                                    <input id="input" type="text" style="width:3px" />
                                                    // jQuery
                                                    $(function(){
                                                    $('#input').keyup(function(){
                                                    $('<span id="width">').append( $(this).val() ).appendTo('body');
                                                    $(this).width( $('#width').width() + 2 );
                                                    $('#width').remove();
                                                    });
                                                    });









                                                    share|improve this answer













                                                    You could do something like this



                                                    // HTML
                                                    <input id="input" type="text" style="width:3px" />
                                                    // jQuery
                                                    $(function(){
                                                    $('#input').keyup(function(){
                                                    $('<span id="width">').append( $(this).val() ).appendTo('body');
                                                    $(this).width( $('#width').width() + 2 );
                                                    $('#width').remove();
                                                    });
                                                    });










                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Aug 2 '10 at 23:44









                                                    TiesTies

                                                    4,29121632




                                                    4,29121632













                                                    • Only if body > span has the exact same styling as #input...

                                                      – Trevor Burnham
                                                      Jun 15 '12 at 22:31











                                                    • If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                      – Lyth
                                                      Feb 13 '13 at 13:35



















                                                    • Only if body > span has the exact same styling as #input...

                                                      – Trevor Burnham
                                                      Jun 15 '12 at 22:31











                                                    • If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                      – Lyth
                                                      Feb 13 '13 at 13:35

















                                                    Only if body > span has the exact same styling as #input...

                                                    – Trevor Burnham
                                                    Jun 15 '12 at 22:31





                                                    Only if body > span has the exact same styling as #input...

                                                    – Trevor Burnham
                                                    Jun 15 '12 at 22:31













                                                    If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                    – Lyth
                                                    Feb 13 '13 at 13:35





                                                    If you increase the size on keyup it will result in an ugly behaviour. Input needs to increase its size just before the character comes into it for more comfort.

                                                    – Lyth
                                                    Feb 13 '13 at 13:35











                                                    7














                                                    Here is an alternative way to solve this using a DIV and the 'contenteditable' property:



                                                    HTML:



                                                    <div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>


                                                    CSS: (to give the DIV some dimensions and make it easier to see)



                                                    .fluidInput {

                                                    display : inline-block;
                                                    vertical-align : top;

                                                    min-width : 1em;
                                                    height : 1.5em;

                                                    font-family : Arial, Helvetica, sans-serif;
                                                    font-size : 0.8em;
                                                    line-height : 1.5em;

                                                    padding : 0px 2px 0px 2px;
                                                    border : 1px solid #aaa;
                                                    cursor : text;
                                                    }


                                                    .fluidInput * {

                                                    display : inline;

                                                    }


                                                    .fluidInput br {

                                                    display : none;

                                                    }


                                                    .fluidInput:empty:before {

                                                    content : attr(data-placeholder);
                                                    color : #ccc;

                                                    }


                                                    Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.






                                                    share|improve this answer





















                                                    • 1





                                                      This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                      – Daniel Bonnell
                                                      Jul 5 '17 at 20:45











                                                    • But it's not an input!

                                                      – Toni Michel Caubet
                                                      May 24 '18 at 17:31
















                                                    7














                                                    Here is an alternative way to solve this using a DIV and the 'contenteditable' property:



                                                    HTML:



                                                    <div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>


                                                    CSS: (to give the DIV some dimensions and make it easier to see)



                                                    .fluidInput {

                                                    display : inline-block;
                                                    vertical-align : top;

                                                    min-width : 1em;
                                                    height : 1.5em;

                                                    font-family : Arial, Helvetica, sans-serif;
                                                    font-size : 0.8em;
                                                    line-height : 1.5em;

                                                    padding : 0px 2px 0px 2px;
                                                    border : 1px solid #aaa;
                                                    cursor : text;
                                                    }


                                                    .fluidInput * {

                                                    display : inline;

                                                    }


                                                    .fluidInput br {

                                                    display : none;

                                                    }


                                                    .fluidInput:empty:before {

                                                    content : attr(data-placeholder);
                                                    color : #ccc;

                                                    }


                                                    Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.






                                                    share|improve this answer





















                                                    • 1





                                                      This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                      – Daniel Bonnell
                                                      Jul 5 '17 at 20:45











                                                    • But it's not an input!

                                                      – Toni Michel Caubet
                                                      May 24 '18 at 17:31














                                                    7












                                                    7








                                                    7







                                                    Here is an alternative way to solve this using a DIV and the 'contenteditable' property:



                                                    HTML:



                                                    <div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>


                                                    CSS: (to give the DIV some dimensions and make it easier to see)



                                                    .fluidInput {

                                                    display : inline-block;
                                                    vertical-align : top;

                                                    min-width : 1em;
                                                    height : 1.5em;

                                                    font-family : Arial, Helvetica, sans-serif;
                                                    font-size : 0.8em;
                                                    line-height : 1.5em;

                                                    padding : 0px 2px 0px 2px;
                                                    border : 1px solid #aaa;
                                                    cursor : text;
                                                    }


                                                    .fluidInput * {

                                                    display : inline;

                                                    }


                                                    .fluidInput br {

                                                    display : none;

                                                    }


                                                    .fluidInput:empty:before {

                                                    content : attr(data-placeholder);
                                                    color : #ccc;

                                                    }


                                                    Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.






                                                    share|improve this answer















                                                    Here is an alternative way to solve this using a DIV and the 'contenteditable' property:



                                                    HTML:



                                                    <div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>


                                                    CSS: (to give the DIV some dimensions and make it easier to see)



                                                    .fluidInput {

                                                    display : inline-block;
                                                    vertical-align : top;

                                                    min-width : 1em;
                                                    height : 1.5em;

                                                    font-family : Arial, Helvetica, sans-serif;
                                                    font-size : 0.8em;
                                                    line-height : 1.5em;

                                                    padding : 0px 2px 0px 2px;
                                                    border : 1px solid #aaa;
                                                    cursor : text;
                                                    }


                                                    .fluidInput * {

                                                    display : inline;

                                                    }


                                                    .fluidInput br {

                                                    display : none;

                                                    }


                                                    .fluidInput:empty:before {

                                                    content : attr(data-placeholder);
                                                    color : #ccc;

                                                    }


                                                    Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML or .html() respectively) of the DIV.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Jan 9 '17 at 11:06

























                                                    answered Jan 9 '17 at 10:09









                                                    logic8logic8

                                                    448617




                                                    448617








                                                    • 1





                                                      This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                      – Daniel Bonnell
                                                      Jul 5 '17 at 20:45











                                                    • But it's not an input!

                                                      – Toni Michel Caubet
                                                      May 24 '18 at 17:31














                                                    • 1





                                                      This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                      – Daniel Bonnell
                                                      Jul 5 '17 at 20:45











                                                    • But it's not an input!

                                                      – Toni Michel Caubet
                                                      May 24 '18 at 17:31








                                                    1




                                                    1





                                                    This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                    – Daniel Bonnell
                                                    Jul 5 '17 at 20:45





                                                    This deserves more upvotes. It's elegant and simple (as long as using JS for form validations isn't a problem for you).

                                                    – Daniel Bonnell
                                                    Jul 5 '17 at 20:45













                                                    But it's not an input!

                                                    – Toni Michel Caubet
                                                    May 24 '18 at 17:31





                                                    But it's not an input!

                                                    – Toni Michel Caubet
                                                    May 24 '18 at 17:31











                                                    4














                                                    Here is a plain JS and a jQuery plugin I wrote that will handle resizing an input element using a canvas and the font size / family to determine the actual string length when rendered. (only works in > IE9, chrome, safari, firefox, opera and most other major browsers that have implemented the canvas element).



                                                    PlainJS:



                                                    function autoSize(input, o) {
                                                    o || (o = {});
                                                    o.on || (o.on = 'keyup');

                                                    var canvas = document.createElement('canvas');
                                                    canvas.setAttribute('style', 'position: absolute; left: -9999px');
                                                    document.body.appendChild(canvas);

                                                    var ctx = canvas.getContext('2d');

                                                    input.addEventListener(o.on, function () {
                                                    ctx.font = getComputedStyle(this,null).getPropertyValue('font');
                                                    this.style.width = ctx.measureText(this.value + ' ').width + 'px';
                                                    });
                                                    }

                                                    //Usage
                                                    autoSize(document.getElementById('my-input'));


                                                    jQuery Plugin:



                                                    $.fn.autoSize = function(o) {
                                                    o = $.extend({}, {
                                                    on: 'keyup'
                                                    }, o);

                                                    var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
                                                    $('body').append($canvas);

                                                    var ctx = $canvas[0].getContext('2d');

                                                    return this.on(o.on, function(){
                                                    var $this = $(this);
                                                    ctx.font = $this.css('font');
                                                    $this.width(ctx.measureText($this.val()).width + 'px');
                                                    })
                                                    }

                                                    //Usage:
                                                    $('#my-input').autoSize();


                                                    Note: this will not handle text-transforms, line spacing and letter spacing, and probably some other text size changing properties. To handle text-transform property set and adjust the text value to match that property. The others are probably fairly straight forward. I will implement if this starts gaining some traction...






                                                    share|improve this answer






























                                                      4














                                                      Here is a plain JS and a jQuery plugin I wrote that will handle resizing an input element using a canvas and the font size / family to determine the actual string length when rendered. (only works in > IE9, chrome, safari, firefox, opera and most other major browsers that have implemented the canvas element).



                                                      PlainJS:



                                                      function autoSize(input, o) {
                                                      o || (o = {});
                                                      o.on || (o.on = 'keyup');

                                                      var canvas = document.createElement('canvas');
                                                      canvas.setAttribute('style', 'position: absolute; left: -9999px');
                                                      document.body.appendChild(canvas);

                                                      var ctx = canvas.getContext('2d');

                                                      input.addEventListener(o.on, function () {
                                                      ctx.font = getComputedStyle(this,null).getPropertyValue('font');
                                                      this.style.width = ctx.measureText(this.value + ' ').width + 'px';
                                                      });
                                                      }

                                                      //Usage
                                                      autoSize(document.getElementById('my-input'));


                                                      jQuery Plugin:



                                                      $.fn.autoSize = function(o) {
                                                      o = $.extend({}, {
                                                      on: 'keyup'
                                                      }, o);

                                                      var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
                                                      $('body').append($canvas);

                                                      var ctx = $canvas[0].getContext('2d');

                                                      return this.on(o.on, function(){
                                                      var $this = $(this);
                                                      ctx.font = $this.css('font');
                                                      $this.width(ctx.measureText($this.val()).width + 'px');
                                                      })
                                                      }

                                                      //Usage:
                                                      $('#my-input').autoSize();


                                                      Note: this will not handle text-transforms, line spacing and letter spacing, and probably some other text size changing properties. To handle text-transform property set and adjust the text value to match that property. The others are probably fairly straight forward. I will implement if this starts gaining some traction...






                                                      share|improve this answer




























                                                        4












                                                        4








                                                        4







                                                        Here is a plain JS and a jQuery plugin I wrote that will handle resizing an input element using a canvas and the font size / family to determine the actual string length when rendered. (only works in > IE9, chrome, safari, firefox, opera and most other major browsers that have implemented the canvas element).



                                                        PlainJS:



                                                        function autoSize(input, o) {
                                                        o || (o = {});
                                                        o.on || (o.on = 'keyup');

                                                        var canvas = document.createElement('canvas');
                                                        canvas.setAttribute('style', 'position: absolute; left: -9999px');
                                                        document.body.appendChild(canvas);

                                                        var ctx = canvas.getContext('2d');

                                                        input.addEventListener(o.on, function () {
                                                        ctx.font = getComputedStyle(this,null).getPropertyValue('font');
                                                        this.style.width = ctx.measureText(this.value + ' ').width + 'px';
                                                        });
                                                        }

                                                        //Usage
                                                        autoSize(document.getElementById('my-input'));


                                                        jQuery Plugin:



                                                        $.fn.autoSize = function(o) {
                                                        o = $.extend({}, {
                                                        on: 'keyup'
                                                        }, o);

                                                        var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
                                                        $('body').append($canvas);

                                                        var ctx = $canvas[0].getContext('2d');

                                                        return this.on(o.on, function(){
                                                        var $this = $(this);
                                                        ctx.font = $this.css('font');
                                                        $this.width(ctx.measureText($this.val()).width + 'px');
                                                        })
                                                        }

                                                        //Usage:
                                                        $('#my-input').autoSize();


                                                        Note: this will not handle text-transforms, line spacing and letter spacing, and probably some other text size changing properties. To handle text-transform property set and adjust the text value to match that property. The others are probably fairly straight forward. I will implement if this starts gaining some traction...






                                                        share|improve this answer















                                                        Here is a plain JS and a jQuery plugin I wrote that will handle resizing an input element using a canvas and the font size / family to determine the actual string length when rendered. (only works in > IE9, chrome, safari, firefox, opera and most other major browsers that have implemented the canvas element).



                                                        PlainJS:



                                                        function autoSize(input, o) {
                                                        o || (o = {});
                                                        o.on || (o.on = 'keyup');

                                                        var canvas = document.createElement('canvas');
                                                        canvas.setAttribute('style', 'position: absolute; left: -9999px');
                                                        document.body.appendChild(canvas);

                                                        var ctx = canvas.getContext('2d');

                                                        input.addEventListener(o.on, function () {
                                                        ctx.font = getComputedStyle(this,null).getPropertyValue('font');
                                                        this.style.width = ctx.measureText(this.value + ' ').width + 'px';
                                                        });
                                                        }

                                                        //Usage
                                                        autoSize(document.getElementById('my-input'));


                                                        jQuery Plugin:



                                                        $.fn.autoSize = function(o) {
                                                        o = $.extend({}, {
                                                        on: 'keyup'
                                                        }, o);

                                                        var $canvas = $('<canvas/>').css({position: 'absolute', left: -9999});
                                                        $('body').append($canvas);

                                                        var ctx = $canvas[0].getContext('2d');

                                                        return this.on(o.on, function(){
                                                        var $this = $(this);
                                                        ctx.font = $this.css('font');
                                                        $this.width(ctx.measureText($this.val()).width + 'px');
                                                        })
                                                        }

                                                        //Usage:
                                                        $('#my-input').autoSize();


                                                        Note: this will not handle text-transforms, line spacing and letter spacing, and probably some other text size changing properties. To handle text-transform property set and adjust the text value to match that property. The others are probably fairly straight forward. I will implement if this starts gaining some traction...







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Sep 2 '15 at 20:36

























                                                        answered Sep 1 '15 at 17:17









                                                        newms87newms87

                                                        5031618




                                                        5031618























                                                            4














                                                            This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:



                                                            <input [style.width.ch]="value.length" [(ngModel)]="value" />


                                                            It automatically updates via the character units in Jani's answer.






                                                            share|improve this answer




























                                                              4














                                                              This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:



                                                              <input [style.width.ch]="value.length" [(ngModel)]="value" />


                                                              It automatically updates via the character units in Jani's answer.






                                                              share|improve this answer


























                                                                4












                                                                4








                                                                4







                                                                This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:



                                                                <input [style.width.ch]="value.length" [(ngModel)]="value" />


                                                                It automatically updates via the character units in Jani's answer.






                                                                share|improve this answer













                                                                This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:



                                                                <input [style.width.ch]="value.length" [(ngModel)]="value" />


                                                                It automatically updates via the character units in Jani's answer.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Dec 7 '17 at 21:49









                                                                Chris VandeveldeChris Vandevelde

                                                                8431220




                                                                8431220























                                                                    2














                                                                    You can do it even simpler in angularjs using the built-in ng-style directive.



                                                                    In your html:



                                                                      <input ng-style="inputStyle(testdata)" ng-model="testdata" />


                                                                    In your controller:



                                                                     $scope.testdata = "whatever";

                                                                    $scope.inputStyle = function(str) {
                                                                    var charWidth = 7;
                                                                    return {"width": (str.length +1) * charWidth + "px" };
                                                                    };


                                                                    In your css:



                                                                    input { font-family:monospace; font-size:12px; }


                                                                    Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;






                                                                    share|improve this answer



















                                                                    • 2





                                                                      This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                      – vlasits
                                                                      Aug 7 '14 at 15:32











                                                                    • How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                      – Ethan
                                                                      May 18 '15 at 15:57











                                                                    • You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                      – Dan Dascalescu
                                                                      Jul 8 '15 at 11:47
















                                                                    2














                                                                    You can do it even simpler in angularjs using the built-in ng-style directive.



                                                                    In your html:



                                                                      <input ng-style="inputStyle(testdata)" ng-model="testdata" />


                                                                    In your controller:



                                                                     $scope.testdata = "whatever";

                                                                    $scope.inputStyle = function(str) {
                                                                    var charWidth = 7;
                                                                    return {"width": (str.length +1) * charWidth + "px" };
                                                                    };


                                                                    In your css:



                                                                    input { font-family:monospace; font-size:12px; }


                                                                    Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;






                                                                    share|improve this answer



















                                                                    • 2





                                                                      This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                      – vlasits
                                                                      Aug 7 '14 at 15:32











                                                                    • How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                      – Ethan
                                                                      May 18 '15 at 15:57











                                                                    • You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                      – Dan Dascalescu
                                                                      Jul 8 '15 at 11:47














                                                                    2












                                                                    2








                                                                    2







                                                                    You can do it even simpler in angularjs using the built-in ng-style directive.



                                                                    In your html:



                                                                      <input ng-style="inputStyle(testdata)" ng-model="testdata" />


                                                                    In your controller:



                                                                     $scope.testdata = "whatever";

                                                                    $scope.inputStyle = function(str) {
                                                                    var charWidth = 7;
                                                                    return {"width": (str.length +1) * charWidth + "px" };
                                                                    };


                                                                    In your css:



                                                                    input { font-family:monospace; font-size:12px; }


                                                                    Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;






                                                                    share|improve this answer













                                                                    You can do it even simpler in angularjs using the built-in ng-style directive.



                                                                    In your html:



                                                                      <input ng-style="inputStyle(testdata)" ng-model="testdata" />


                                                                    In your controller:



                                                                     $scope.testdata = "whatever";

                                                                    $scope.inputStyle = function(str) {
                                                                    var charWidth = 7;
                                                                    return {"width": (str.length +1) * charWidth + "px" };
                                                                    };


                                                                    In your css:



                                                                    input { font-family:monospace; font-size:12px; }


                                                                    Adjust the charWidth to match the width of your font. It seems to be 7 at a font-size of 12px;







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jul 20 '13 at 2:22









                                                                    michieljorismichieljoris

                                                                    57152




                                                                    57152








                                                                    • 2





                                                                      This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                      – vlasits
                                                                      Aug 7 '14 at 15:32











                                                                    • How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                      – Ethan
                                                                      May 18 '15 at 15:57











                                                                    • You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                      – Dan Dascalescu
                                                                      Jul 8 '15 at 11:47














                                                                    • 2





                                                                      This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                      – vlasits
                                                                      Aug 7 '14 at 15:32











                                                                    • How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                      – Ethan
                                                                      May 18 '15 at 15:57











                                                                    • You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                      – Dan Dascalescu
                                                                      Jul 8 '15 at 11:47








                                                                    2




                                                                    2





                                                                    This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                    – vlasits
                                                                    Aug 7 '14 at 15:32





                                                                    This is cool and handy to know, but adding angularjs to an app to dynamically resize an input element is really serious overkill especially when OP asked for "HTML, JavaScript, PHP or CSS" solutions. One could argue that jQuery is overkill for this, too, but--unlike Angular--being a DOM-manipulation toolkit is core to jQuery's purpose.

                                                                    – vlasits
                                                                    Aug 7 '14 at 15:32













                                                                    How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                    – Ethan
                                                                    May 18 '15 at 15:57





                                                                    How am I supposed to know the width of the character being typed? It's not easy to assume it is a mono-sized font.

                                                                    – Ethan
                                                                    May 18 '15 at 15:57













                                                                    You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                    – Dan Dascalescu
                                                                    Jul 8 '15 at 11:47





                                                                    You can't require a monospaced font, and there's no need for Angular. brendan's answer does basically the same.

                                                                    – Dan Dascalescu
                                                                    Jul 8 '15 at 11:47











                                                                    2














                                                                    It's worth noting that a nice-looking resize can be done when the font is monospaced, so we can perfectly resize the input element using the ch unit.



                                                                    Also in this approach we can update the width of the field by just updating a CSS variable (custom property) on input event and we should also take care of already pre-filled input on DOMContentLoaded event




                                                                    Codepen demo






                                                                    Markup



                                                                    <input type="text" value="space mono font" class="selfadapt" />


                                                                    CSS



                                                                    :root { --size: 0; }

                                                                    .selfadapt {
                                                                    padding: 5px;
                                                                    min-width: 10ch;
                                                                    font-family: "space mono";
                                                                    font-size: 1.5rem;
                                                                    width: calc(var(--size) * 1ch);
                                                                    }


                                                                    As a root variable we set --size: 0: this variable will contain the length of the input and it will be multiplied by 1ch inside the calc() expression. By default we could also set a min-width, e.g. 10ch



                                                                    The Javascript part reads the length of the value inserted and updates the variable --size:



                                                                    JS



                                                                    let input = document.querySelector('.selfadapt');
                                                                    let root = document.documentElement.style;

                                                                    /* on input event auto resize the field */
                                                                    input.addEventListener('input', function() {
                                                                    root.setProperty('--size', this.value.length );
                                                                    });

                                                                    /* resize the field if it is pre-populated */
                                                                    document.addEventListener("DOMContentLoaded", function() {
                                                                    root.setProperty('--size', input.value.length);
                                                                    });


                                                                    of course this still works even if you don't use monospaced font, but in that case you will need to change the calc() formula by multiplying the --size variable by another value (which it's strictly dependent on the font-family and font-size) different than 1ch.






                                                                    share|improve this answer




























                                                                      2














                                                                      It's worth noting that a nice-looking resize can be done when the font is monospaced, so we can perfectly resize the input element using the ch unit.



                                                                      Also in this approach we can update the width of the field by just updating a CSS variable (custom property) on input event and we should also take care of already pre-filled input on DOMContentLoaded event




                                                                      Codepen demo






                                                                      Markup



                                                                      <input type="text" value="space mono font" class="selfadapt" />


                                                                      CSS



                                                                      :root { --size: 0; }

                                                                      .selfadapt {
                                                                      padding: 5px;
                                                                      min-width: 10ch;
                                                                      font-family: "space mono";
                                                                      font-size: 1.5rem;
                                                                      width: calc(var(--size) * 1ch);
                                                                      }


                                                                      As a root variable we set --size: 0: this variable will contain the length of the input and it will be multiplied by 1ch inside the calc() expression. By default we could also set a min-width, e.g. 10ch



                                                                      The Javascript part reads the length of the value inserted and updates the variable --size:



                                                                      JS



                                                                      let input = document.querySelector('.selfadapt');
                                                                      let root = document.documentElement.style;

                                                                      /* on input event auto resize the field */
                                                                      input.addEventListener('input', function() {
                                                                      root.setProperty('--size', this.value.length );
                                                                      });

                                                                      /* resize the field if it is pre-populated */
                                                                      document.addEventListener("DOMContentLoaded", function() {
                                                                      root.setProperty('--size', input.value.length);
                                                                      });


                                                                      of course this still works even if you don't use monospaced font, but in that case you will need to change the calc() formula by multiplying the --size variable by another value (which it's strictly dependent on the font-family and font-size) different than 1ch.






                                                                      share|improve this answer


























                                                                        2












                                                                        2








                                                                        2







                                                                        It's worth noting that a nice-looking resize can be done when the font is monospaced, so we can perfectly resize the input element using the ch unit.



                                                                        Also in this approach we can update the width of the field by just updating a CSS variable (custom property) on input event and we should also take care of already pre-filled input on DOMContentLoaded event




                                                                        Codepen demo






                                                                        Markup



                                                                        <input type="text" value="space mono font" class="selfadapt" />


                                                                        CSS



                                                                        :root { --size: 0; }

                                                                        .selfadapt {
                                                                        padding: 5px;
                                                                        min-width: 10ch;
                                                                        font-family: "space mono";
                                                                        font-size: 1.5rem;
                                                                        width: calc(var(--size) * 1ch);
                                                                        }


                                                                        As a root variable we set --size: 0: this variable will contain the length of the input and it will be multiplied by 1ch inside the calc() expression. By default we could also set a min-width, e.g. 10ch



                                                                        The Javascript part reads the length of the value inserted and updates the variable --size:



                                                                        JS



                                                                        let input = document.querySelector('.selfadapt');
                                                                        let root = document.documentElement.style;

                                                                        /* on input event auto resize the field */
                                                                        input.addEventListener('input', function() {
                                                                        root.setProperty('--size', this.value.length );
                                                                        });

                                                                        /* resize the field if it is pre-populated */
                                                                        document.addEventListener("DOMContentLoaded", function() {
                                                                        root.setProperty('--size', input.value.length);
                                                                        });


                                                                        of course this still works even if you don't use monospaced font, but in that case you will need to change the calc() formula by multiplying the --size variable by another value (which it's strictly dependent on the font-family and font-size) different than 1ch.






                                                                        share|improve this answer













                                                                        It's worth noting that a nice-looking resize can be done when the font is monospaced, so we can perfectly resize the input element using the ch unit.



                                                                        Also in this approach we can update the width of the field by just updating a CSS variable (custom property) on input event and we should also take care of already pre-filled input on DOMContentLoaded event




                                                                        Codepen demo






                                                                        Markup



                                                                        <input type="text" value="space mono font" class="selfadapt" />


                                                                        CSS



                                                                        :root { --size: 0; }

                                                                        .selfadapt {
                                                                        padding: 5px;
                                                                        min-width: 10ch;
                                                                        font-family: "space mono";
                                                                        font-size: 1.5rem;
                                                                        width: calc(var(--size) * 1ch);
                                                                        }


                                                                        As a root variable we set --size: 0: this variable will contain the length of the input and it will be multiplied by 1ch inside the calc() expression. By default we could also set a min-width, e.g. 10ch



                                                                        The Javascript part reads the length of the value inserted and updates the variable --size:



                                                                        JS



                                                                        let input = document.querySelector('.selfadapt');
                                                                        let root = document.documentElement.style;

                                                                        /* on input event auto resize the field */
                                                                        input.addEventListener('input', function() {
                                                                        root.setProperty('--size', this.value.length );
                                                                        });

                                                                        /* resize the field if it is pre-populated */
                                                                        document.addEventListener("DOMContentLoaded", function() {
                                                                        root.setProperty('--size', input.value.length);
                                                                        });


                                                                        of course this still works even if you don't use monospaced font, but in that case you will need to change the calc() formula by multiplying the --size variable by another value (which it's strictly dependent on the font-family and font-size) different than 1ch.







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Jun 4 '18 at 10:56









                                                                        fcalderanfcalderan

                                                                        88.6k18128142




                                                                        88.6k18128142























                                                                            1














                                                                            I think you're misinterpreting the min-width CSS property. min-width is generally used to define a minimum DOM width in a fluid layout, like:



                                                                            input {
                                                                            width: 30%;
                                                                            min-width: 200px;
                                                                            }


                                                                            That would set the input element to a minimum width of 200 pixels. In this context, "px" stands for "pixels".



                                                                            Now, if you're trying to check to make sure that input field contains at least one character when a user submits it, you'll need to do some form validation with JavaScript and PHP. If that is indeed what you're attempting to do, I'll edit this answer and do my best to help you out.






                                                                            share|improve this answer
























                                                                            • i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:30






                                                                            • 1





                                                                              @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                              – Marcel Korpel
                                                                              Aug 2 '10 at 23:36











                                                                            • Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:40











                                                                            • Perhaps there is a php function for this, anybody knows ?

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:43











                                                                            • I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                              – peterjmag
                                                                              Aug 2 '10 at 23:48
















                                                                            1














                                                                            I think you're misinterpreting the min-width CSS property. min-width is generally used to define a minimum DOM width in a fluid layout, like:



                                                                            input {
                                                                            width: 30%;
                                                                            min-width: 200px;
                                                                            }


                                                                            That would set the input element to a minimum width of 200 pixels. In this context, "px" stands for "pixels".



                                                                            Now, if you're trying to check to make sure that input field contains at least one character when a user submits it, you'll need to do some form validation with JavaScript and PHP. If that is indeed what you're attempting to do, I'll edit this answer and do my best to help you out.






                                                                            share|improve this answer
























                                                                            • i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:30






                                                                            • 1





                                                                              @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                              – Marcel Korpel
                                                                              Aug 2 '10 at 23:36











                                                                            • Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:40











                                                                            • Perhaps there is a php function for this, anybody knows ?

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:43











                                                                            • I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                              – peterjmag
                                                                              Aug 2 '10 at 23:48














                                                                            1












                                                                            1








                                                                            1







                                                                            I think you're misinterpreting the min-width CSS property. min-width is generally used to define a minimum DOM width in a fluid layout, like:



                                                                            input {
                                                                            width: 30%;
                                                                            min-width: 200px;
                                                                            }


                                                                            That would set the input element to a minimum width of 200 pixels. In this context, "px" stands for "pixels".



                                                                            Now, if you're trying to check to make sure that input field contains at least one character when a user submits it, you'll need to do some form validation with JavaScript and PHP. If that is indeed what you're attempting to do, I'll edit this answer and do my best to help you out.






                                                                            share|improve this answer













                                                                            I think you're misinterpreting the min-width CSS property. min-width is generally used to define a minimum DOM width in a fluid layout, like:



                                                                            input {
                                                                            width: 30%;
                                                                            min-width: 200px;
                                                                            }


                                                                            That would set the input element to a minimum width of 200 pixels. In this context, "px" stands for "pixels".



                                                                            Now, if you're trying to check to make sure that input field contains at least one character when a user submits it, you'll need to do some form validation with JavaScript and PHP. If that is indeed what you're attempting to do, I'll edit this answer and do my best to help you out.







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Aug 2 '10 at 23:28









                                                                            peterjmagpeterjmag

                                                                            4,64012326




                                                                            4,64012326













                                                                            • i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:30






                                                                            • 1





                                                                              @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                              – Marcel Korpel
                                                                              Aug 2 '10 at 23:36











                                                                            • Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:40











                                                                            • Perhaps there is a php function for this, anybody knows ?

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:43











                                                                            • I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                              – peterjmag
                                                                              Aug 2 '10 at 23:48



















                                                                            • i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:30






                                                                            • 1





                                                                              @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                              – Marcel Korpel
                                                                              Aug 2 '10 at 23:36











                                                                            • Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:40











                                                                            • Perhaps there is a php function for this, anybody knows ?

                                                                              – Kerc
                                                                              Aug 2 '10 at 23:43











                                                                            • I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                              – peterjmag
                                                                              Aug 2 '10 at 23:48

















                                                                            i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:30





                                                                            i know what px means and i know javascript has a function for min-width but it ain't working for input text.

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:30




                                                                            1




                                                                            1





                                                                            @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                            – Marcel Korpel
                                                                            Aug 2 '10 at 23:36





                                                                            @Kerc: “javascript has a function for min-width” - which one? What do you mean? – “it ain't working” is never a good description of a problem. Try to elaborate on the intended behaviour.

                                                                            – Marcel Korpel
                                                                            Aug 2 '10 at 23:36













                                                                            Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:40





                                                                            Did you even try my example, than you see that it ain't 1 px and yours ain't also. This ain't going to work no matter if i write it in html, css

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:40













                                                                            Perhaps there is a php function for this, anybody knows ?

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:43





                                                                            Perhaps there is a php function for this, anybody knows ?

                                                                            – Kerc
                                                                            Aug 2 '10 at 23:43













                                                                            I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                            – peterjmag
                                                                            Aug 2 '10 at 23:48





                                                                            I did try your example, but I assumed that a 1 pixel wide input field wasn't what you were looking for. If it is, try <input type="text" value="1" style="width:1px;" />

                                                                            – peterjmag
                                                                            Aug 2 '10 at 23:48











                                                                            1














                                                                            I really liked Lyth's answer, but also really wanted it to:




                                                                            1. Handle backspace and delete

                                                                            2. Not require you to manually add an adjacent tag.

                                                                            3. Enforce a min width.

                                                                            4. Automatically be applied to elements with a specific class


                                                                            I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.



                                                                            HTML:



                                                                            <div id='applicationHost'>
                                                                            <div>Name: <input class='textbox-autosize' data-min-width='100' type="text" /></div>
                                                                            <div>Email: <input class='textbox-autosize' data-min-width='100' type="email" /></div>
                                                                            <div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
                                                                            </div>


                                                                            CSS:



                                                                            #applicationHost {
                                                                            font-family: courier;
                                                                            white-space: pre;
                                                                            }

                                                                            input.textbox-autosize, span.invisible-autosize-helper {
                                                                            padding:0;
                                                                            font-size:12px;
                                                                            font-family:Sans-serif;
                                                                            white-space:pre;
                                                                            }
                                                                            input.textbox-autosize {
                                                                            width: 100px; /* Initial width of textboxes */
                                                                            }

                                                                            /*
                                                                            In order for the measurements to work out, your input and the invisible
                                                                            span need to have the same styling.
                                                                            */


                                                                            JavaScript:



                                                                            $('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
                                                                            // Add an arbitary buffer of 15 pixels.
                                                                            var whitespaceBuffer = 15;
                                                                            var je = $(this);
                                                                            var minWidth = parseInt(je.attr('data-min-width'));
                                                                            var newVal = je.val();
                                                                            var sizingSpanClass = 'invisible-autosize-helper';
                                                                            var $span = je.siblings('span.' + sizingSpanClass).first();
                                                                            // If this element hasn't been created yet, we'll create it now.
                                                                            if ($span.length === 0) {
                                                                            $span = $('<span/>', {
                                                                            'class': sizingSpanClass,
                                                                            'style': 'display: none;'
                                                                            });
                                                                            je.parent().append($span);
                                                                            }
                                                                            $span = je.siblings('span').first();
                                                                            $span.text(newVal) ; // the hidden span takes
                                                                            // the value of the input
                                                                            $inputSize = $span.width();
                                                                            $inputSize += whitespaceBuffer;
                                                                            if($inputSize > minWidth)
                                                                            je.css("width", $inputSize) ; // apply width of the span to the input
                                                                            else
                                                                            je.css("width", minWidth) ; // Ensure we're at the min width
                                                                            });





                                                                            share|improve this answer






























                                                                              1














                                                                              I really liked Lyth's answer, but also really wanted it to:




                                                                              1. Handle backspace and delete

                                                                              2. Not require you to manually add an adjacent tag.

                                                                              3. Enforce a min width.

                                                                              4. Automatically be applied to elements with a specific class


                                                                              I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.



                                                                              HTML:



                                                                              <div id='applicationHost'>
                                                                              <div>Name: <input class='textbox-autosize' data-min-width='100' type="text" /></div>
                                                                              <div>Email: <input class='textbox-autosize' data-min-width='100' type="email" /></div>
                                                                              <div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
                                                                              </div>


                                                                              CSS:



                                                                              #applicationHost {
                                                                              font-family: courier;
                                                                              white-space: pre;
                                                                              }

                                                                              input.textbox-autosize, span.invisible-autosize-helper {
                                                                              padding:0;
                                                                              font-size:12px;
                                                                              font-family:Sans-serif;
                                                                              white-space:pre;
                                                                              }
                                                                              input.textbox-autosize {
                                                                              width: 100px; /* Initial width of textboxes */
                                                                              }

                                                                              /*
                                                                              In order for the measurements to work out, your input and the invisible
                                                                              span need to have the same styling.
                                                                              */


                                                                              JavaScript:



                                                                              $('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
                                                                              // Add an arbitary buffer of 15 pixels.
                                                                              var whitespaceBuffer = 15;
                                                                              var je = $(this);
                                                                              var minWidth = parseInt(je.attr('data-min-width'));
                                                                              var newVal = je.val();
                                                                              var sizingSpanClass = 'invisible-autosize-helper';
                                                                              var $span = je.siblings('span.' + sizingSpanClass).first();
                                                                              // If this element hasn't been created yet, we'll create it now.
                                                                              if ($span.length === 0) {
                                                                              $span = $('<span/>', {
                                                                              'class': sizingSpanClass,
                                                                              'style': 'display: none;'
                                                                              });
                                                                              je.parent().append($span);
                                                                              }
                                                                              $span = je.siblings('span').first();
                                                                              $span.text(newVal) ; // the hidden span takes
                                                                              // the value of the input
                                                                              $inputSize = $span.width();
                                                                              $inputSize += whitespaceBuffer;
                                                                              if($inputSize > minWidth)
                                                                              je.css("width", $inputSize) ; // apply width of the span to the input
                                                                              else
                                                                              je.css("width", minWidth) ; // Ensure we're at the min width
                                                                              });





                                                                              share|improve this answer




























                                                                                1












                                                                                1








                                                                                1







                                                                                I really liked Lyth's answer, but also really wanted it to:




                                                                                1. Handle backspace and delete

                                                                                2. Not require you to manually add an adjacent tag.

                                                                                3. Enforce a min width.

                                                                                4. Automatically be applied to elements with a specific class


                                                                                I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.



                                                                                HTML:



                                                                                <div id='applicationHost'>
                                                                                <div>Name: <input class='textbox-autosize' data-min-width='100' type="text" /></div>
                                                                                <div>Email: <input class='textbox-autosize' data-min-width='100' type="email" /></div>
                                                                                <div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
                                                                                </div>


                                                                                CSS:



                                                                                #applicationHost {
                                                                                font-family: courier;
                                                                                white-space: pre;
                                                                                }

                                                                                input.textbox-autosize, span.invisible-autosize-helper {
                                                                                padding:0;
                                                                                font-size:12px;
                                                                                font-family:Sans-serif;
                                                                                white-space:pre;
                                                                                }
                                                                                input.textbox-autosize {
                                                                                width: 100px; /* Initial width of textboxes */
                                                                                }

                                                                                /*
                                                                                In order for the measurements to work out, your input and the invisible
                                                                                span need to have the same styling.
                                                                                */


                                                                                JavaScript:



                                                                                $('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
                                                                                // Add an arbitary buffer of 15 pixels.
                                                                                var whitespaceBuffer = 15;
                                                                                var je = $(this);
                                                                                var minWidth = parseInt(je.attr('data-min-width'));
                                                                                var newVal = je.val();
                                                                                var sizingSpanClass = 'invisible-autosize-helper';
                                                                                var $span = je.siblings('span.' + sizingSpanClass).first();
                                                                                // If this element hasn't been created yet, we'll create it now.
                                                                                if ($span.length === 0) {
                                                                                $span = $('<span/>', {
                                                                                'class': sizingSpanClass,
                                                                                'style': 'display: none;'
                                                                                });
                                                                                je.parent().append($span);
                                                                                }
                                                                                $span = je.siblings('span').first();
                                                                                $span.text(newVal) ; // the hidden span takes
                                                                                // the value of the input
                                                                                $inputSize = $span.width();
                                                                                $inputSize += whitespaceBuffer;
                                                                                if($inputSize > minWidth)
                                                                                je.css("width", $inputSize) ; // apply width of the span to the input
                                                                                else
                                                                                je.css("width", minWidth) ; // Ensure we're at the min width
                                                                                });





                                                                                share|improve this answer















                                                                                I really liked Lyth's answer, but also really wanted it to:




                                                                                1. Handle backspace and delete

                                                                                2. Not require you to manually add an adjacent tag.

                                                                                3. Enforce a min width.

                                                                                4. Automatically be applied to elements with a specific class


                                                                                I adapted his JSFiddle and came up with this. One improvement not present in this fiddle would be to use something like the jQuery CSS Parser to actually read the initial width from the input.textbox-autosize rule, and use that as the minWidth. Right I'm simply using an attribute on the , which makes for a compact demo but is not ideal. as it requires an extra attribute on each input. You might also just want to put the minWidth as 100 right in the JavaScript.



                                                                                HTML:



                                                                                <div id='applicationHost'>
                                                                                <div>Name: <input class='textbox-autosize' data-min-width='100' type="text" /></div>
                                                                                <div>Email: <input class='textbox-autosize' data-min-width='100' type="email" /></div>
                                                                                <div>Points: <input class='textbox-autosize' data-min-width='100' type="number" /></div>
                                                                                </div>


                                                                                CSS:



                                                                                #applicationHost {
                                                                                font-family: courier;
                                                                                white-space: pre;
                                                                                }

                                                                                input.textbox-autosize, span.invisible-autosize-helper {
                                                                                padding:0;
                                                                                font-size:12px;
                                                                                font-family:Sans-serif;
                                                                                white-space:pre;
                                                                                }
                                                                                input.textbox-autosize {
                                                                                width: 100px; /* Initial width of textboxes */
                                                                                }

                                                                                /*
                                                                                In order for the measurements to work out, your input and the invisible
                                                                                span need to have the same styling.
                                                                                */


                                                                                JavaScript:



                                                                                $('#applicationHost').on('keyup', '.textbox-autosize', function(e) {
                                                                                // Add an arbitary buffer of 15 pixels.
                                                                                var whitespaceBuffer = 15;
                                                                                var je = $(this);
                                                                                var minWidth = parseInt(je.attr('data-min-width'));
                                                                                var newVal = je.val();
                                                                                var sizingSpanClass = 'invisible-autosize-helper';
                                                                                var $span = je.siblings('span.' + sizingSpanClass).first();
                                                                                // If this element hasn't been created yet, we'll create it now.
                                                                                if ($span.length === 0) {
                                                                                $span = $('<span/>', {
                                                                                'class': sizingSpanClass,
                                                                                'style': 'display: none;'
                                                                                });
                                                                                je.parent().append($span);
                                                                                }
                                                                                $span = je.siblings('span').first();
                                                                                $span.text(newVal) ; // the hidden span takes
                                                                                // the value of the input
                                                                                $inputSize = $span.width();
                                                                                $inputSize += whitespaceBuffer;
                                                                                if($inputSize > minWidth)
                                                                                je.css("width", $inputSize) ; // apply width of the span to the input
                                                                                else
                                                                                je.css("width", minWidth) ; // Ensure we're at the min width
                                                                                });






                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited May 23 '17 at 11:54









                                                                                Community

                                                                                11




                                                                                11










                                                                                answered Jun 26 '14 at 21:16









                                                                                JoshJosh

                                                                                3,29543761




                                                                                3,29543761























                                                                                    1














                                                                                    Just adding on top of other answers.



                                                                                    I noticed that nowadays in some browsers the input field has a scrollWidth. Which means:



                                                                                    this.style.width = this.scrollWidth + 'px';


                                                                                    should work nicely. tested in chrome, firefox and safari.



                                                                                    For deletion support, you can add '=0' first and then readjust.



                                                                                    this.style.width = 0; this.style.width = this.scrollWidth + 'px';





                                                                                    share|improve this answer





















                                                                                    • 3





                                                                                      Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                      – Uooo
                                                                                      Jul 2 '13 at 5:45






                                                                                    • 1





                                                                                      This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                      – Form
                                                                                      Nov 10 '18 at 19:12
















                                                                                    1














                                                                                    Just adding on top of other answers.



                                                                                    I noticed that nowadays in some browsers the input field has a scrollWidth. Which means:



                                                                                    this.style.width = this.scrollWidth + 'px';


                                                                                    should work nicely. tested in chrome, firefox and safari.



                                                                                    For deletion support, you can add '=0' first and then readjust.



                                                                                    this.style.width = 0; this.style.width = this.scrollWidth + 'px';





                                                                                    share|improve this answer





















                                                                                    • 3





                                                                                      Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                      – Uooo
                                                                                      Jul 2 '13 at 5:45






                                                                                    • 1





                                                                                      This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                      – Form
                                                                                      Nov 10 '18 at 19:12














                                                                                    1












                                                                                    1








                                                                                    1







                                                                                    Just adding on top of other answers.



                                                                                    I noticed that nowadays in some browsers the input field has a scrollWidth. Which means:



                                                                                    this.style.width = this.scrollWidth + 'px';


                                                                                    should work nicely. tested in chrome, firefox and safari.



                                                                                    For deletion support, you can add '=0' first and then readjust.



                                                                                    this.style.width = 0; this.style.width = this.scrollWidth + 'px';





                                                                                    share|improve this answer















                                                                                    Just adding on top of other answers.



                                                                                    I noticed that nowadays in some browsers the input field has a scrollWidth. Which means:



                                                                                    this.style.width = this.scrollWidth + 'px';


                                                                                    should work nicely. tested in chrome, firefox and safari.



                                                                                    For deletion support, you can add '=0' first and then readjust.



                                                                                    this.style.width = 0; this.style.width = this.scrollWidth + 'px';






                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    edited May 16 '18 at 21:24

























                                                                                    answered Jul 2 '13 at 5:42









                                                                                    guy mograbiguy mograbi

                                                                                    11.5k65698




                                                                                    11.5k65698








                                                                                    • 3





                                                                                      Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                      – Uooo
                                                                                      Jul 2 '13 at 5:45






                                                                                    • 1





                                                                                      This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                      – Form
                                                                                      Nov 10 '18 at 19:12














                                                                                    • 3





                                                                                      Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                      – Uooo
                                                                                      Jul 2 '13 at 5:45






                                                                                    • 1





                                                                                      This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                      – Form
                                                                                      Nov 10 '18 at 19:12








                                                                                    3




                                                                                    3





                                                                                    Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                    – Uooo
                                                                                    Jul 2 '13 at 5:45





                                                                                    Please add relevant code here as well - the link might be dead in the future and then this post is useless.

                                                                                    – Uooo
                                                                                    Jul 2 '13 at 5:45




                                                                                    1




                                                                                    1





                                                                                    This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                    – Form
                                                                                    Nov 10 '18 at 19:12





                                                                                    This works great, thanks! I don't know why this answer doesn't have more upvotes. It's by far the simplest, less contrived (js) solution.

                                                                                    – Form
                                                                                    Nov 10 '18 at 19:12











                                                                                    1














                                                                                    If you use Bootstrap, it could be done very easily:



                                                                                    <div contenteditable="true" class="form-control" style="display: inline"></div>



                                                                                    You will just need to fetch div's content and put it in a hidden input before submitting the form.






                                                                                    share|improve this answer




























                                                                                      1














                                                                                      If you use Bootstrap, it could be done very easily:



                                                                                      <div contenteditable="true" class="form-control" style="display: inline"></div>



                                                                                      You will just need to fetch div's content and put it in a hidden input before submitting the form.






                                                                                      share|improve this answer


























                                                                                        1












                                                                                        1








                                                                                        1







                                                                                        If you use Bootstrap, it could be done very easily:



                                                                                        <div contenteditable="true" class="form-control" style="display: inline"></div>



                                                                                        You will just need to fetch div's content and put it in a hidden input before submitting the form.






                                                                                        share|improve this answer













                                                                                        If you use Bootstrap, it could be done very easily:



                                                                                        <div contenteditable="true" class="form-control" style="display: inline"></div>



                                                                                        You will just need to fetch div's content and put it in a hidden input before submitting the form.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Jul 9 '18 at 12:54









                                                                                        Alexey KosovAlexey Kosov

                                                                                        1,5561319




                                                                                        1,5561319























                                                                                            0














                                                                                            I just spend some time figuring out how to do it.

                                                                                            Actually the simplest way I found is to move input value to span just before the input, keeping input 1 symbol width. Though I can't be sure that it fit for your initial need.

                                                                                            Maybe it some extra code, but in react+flux based application it is quite natural solution.






                                                                                            share|improve this answer




























                                                                                              0














                                                                                              I just spend some time figuring out how to do it.

                                                                                              Actually the simplest way I found is to move input value to span just before the input, keeping input 1 symbol width. Though I can't be sure that it fit for your initial need.

                                                                                              Maybe it some extra code, but in react+flux based application it is quite natural solution.






                                                                                              share|improve this answer


























                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                I just spend some time figuring out how to do it.

                                                                                                Actually the simplest way I found is to move input value to span just before the input, keeping input 1 symbol width. Though I can't be sure that it fit for your initial need.

                                                                                                Maybe it some extra code, but in react+flux based application it is quite natural solution.






                                                                                                share|improve this answer













                                                                                                I just spend some time figuring out how to do it.

                                                                                                Actually the simplest way I found is to move input value to span just before the input, keeping input 1 symbol width. Though I can't be sure that it fit for your initial need.

                                                                                                Maybe it some extra code, but in react+flux based application it is quite natural solution.







                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Jan 8 '16 at 20:14









                                                                                                freelefreele

                                                                                                1277




                                                                                                1277























                                                                                                    0














                                                                                                    Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.



                                                                                                    I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup and blur are called.



                                                                                                    Here is a working codepen. This codepen shows how this can be used with multiple input fields.



                                                                                                    HTML Structure:



                                                                                                    <input type="text" class="plain-field" placeholder="Full Name">
                                                                                                    <span style="display: none;"></span>


                                                                                                    jQuery:



                                                                                                    function resizeInputs($text) {
                                                                                                    var text = $text.val().replace(/s+/g, ' '),
                                                                                                    placeholder = $text.attr('placeholder'),
                                                                                                    span = $text.next('span');
                                                                                                    span.text(placeholder);
                                                                                                    var width = span.width();

                                                                                                    if(text !== '') {
                                                                                                    span.text(text);
                                                                                                    var width = span.width();
                                                                                                    }

                                                                                                    $text.css('width', width + 5);
                                                                                                    };


                                                                                                    The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5 on the width is because without that the input gets cut off a tiny bit in the Edge Browser.



                                                                                                    $('.plain-field').each(function() {
                                                                                                    var $text = $(this);
                                                                                                    resizeInputs($text);
                                                                                                    });

                                                                                                    $('.plain-field').on('keyup blur', function() {
                                                                                                    var $text = $(this);
                                                                                                    resizeInputs($text);
                                                                                                    });

                                                                                                    $('.plain-field').on('blur', function() {
                                                                                                    var $text = $(this).val().replace(/s+/g, ' ');
                                                                                                    $(this).val($text);
                                                                                                    });


                                                                                                    If this could be improved please let me know as this is the cleanest solution I could come up with.






                                                                                                    share|improve this answer




























                                                                                                      0














                                                                                                      Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.



                                                                                                      I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup and blur are called.



                                                                                                      Here is a working codepen. This codepen shows how this can be used with multiple input fields.



                                                                                                      HTML Structure:



                                                                                                      <input type="text" class="plain-field" placeholder="Full Name">
                                                                                                      <span style="display: none;"></span>


                                                                                                      jQuery:



                                                                                                      function resizeInputs($text) {
                                                                                                      var text = $text.val().replace(/s+/g, ' '),
                                                                                                      placeholder = $text.attr('placeholder'),
                                                                                                      span = $text.next('span');
                                                                                                      span.text(placeholder);
                                                                                                      var width = span.width();

                                                                                                      if(text !== '') {
                                                                                                      span.text(text);
                                                                                                      var width = span.width();
                                                                                                      }

                                                                                                      $text.css('width', width + 5);
                                                                                                      };


                                                                                                      The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5 on the width is because without that the input gets cut off a tiny bit in the Edge Browser.



                                                                                                      $('.plain-field').each(function() {
                                                                                                      var $text = $(this);
                                                                                                      resizeInputs($text);
                                                                                                      });

                                                                                                      $('.plain-field').on('keyup blur', function() {
                                                                                                      var $text = $(this);
                                                                                                      resizeInputs($text);
                                                                                                      });

                                                                                                      $('.plain-field').on('blur', function() {
                                                                                                      var $text = $(this).val().replace(/s+/g, ' ');
                                                                                                      $(this).val($text);
                                                                                                      });


                                                                                                      If this could be improved please let me know as this is the cleanest solution I could come up with.






                                                                                                      share|improve this answer


























                                                                                                        0












                                                                                                        0








                                                                                                        0







                                                                                                        Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.



                                                                                                        I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup and blur are called.



                                                                                                        Here is a working codepen. This codepen shows how this can be used with multiple input fields.



                                                                                                        HTML Structure:



                                                                                                        <input type="text" class="plain-field" placeholder="Full Name">
                                                                                                        <span style="display: none;"></span>


                                                                                                        jQuery:



                                                                                                        function resizeInputs($text) {
                                                                                                        var text = $text.val().replace(/s+/g, ' '),
                                                                                                        placeholder = $text.attr('placeholder'),
                                                                                                        span = $text.next('span');
                                                                                                        span.text(placeholder);
                                                                                                        var width = span.width();

                                                                                                        if(text !== '') {
                                                                                                        span.text(text);
                                                                                                        var width = span.width();
                                                                                                        }

                                                                                                        $text.css('width', width + 5);
                                                                                                        };


                                                                                                        The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5 on the width is because without that the input gets cut off a tiny bit in the Edge Browser.



                                                                                                        $('.plain-field').each(function() {
                                                                                                        var $text = $(this);
                                                                                                        resizeInputs($text);
                                                                                                        });

                                                                                                        $('.plain-field').on('keyup blur', function() {
                                                                                                        var $text = $(this);
                                                                                                        resizeInputs($text);
                                                                                                        });

                                                                                                        $('.plain-field').on('blur', function() {
                                                                                                        var $text = $(this).val().replace(/s+/g, ' ');
                                                                                                        $(this).val($text);
                                                                                                        });


                                                                                                        If this could be improved please let me know as this is the cleanest solution I could come up with.






                                                                                                        share|improve this answer













                                                                                                        Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.



                                                                                                        I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions keyup and blur are called.



                                                                                                        Here is a working codepen. This codepen shows how this can be used with multiple input fields.



                                                                                                        HTML Structure:



                                                                                                        <input type="text" class="plain-field" placeholder="Full Name">
                                                                                                        <span style="display: none;"></span>


                                                                                                        jQuery:



                                                                                                        function resizeInputs($text) {
                                                                                                        var text = $text.val().replace(/s+/g, ' '),
                                                                                                        placeholder = $text.attr('placeholder'),
                                                                                                        span = $text.next('span');
                                                                                                        span.text(placeholder);
                                                                                                        var width = span.width();

                                                                                                        if(text !== '') {
                                                                                                        span.text(text);
                                                                                                        var width = span.width();
                                                                                                        }

                                                                                                        $text.css('width', width + 5);
                                                                                                        };


                                                                                                        The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The + 5 on the width is because without that the input gets cut off a tiny bit in the Edge Browser.



                                                                                                        $('.plain-field').each(function() {
                                                                                                        var $text = $(this);
                                                                                                        resizeInputs($text);
                                                                                                        });

                                                                                                        $('.plain-field').on('keyup blur', function() {
                                                                                                        var $text = $(this);
                                                                                                        resizeInputs($text);
                                                                                                        });

                                                                                                        $('.plain-field').on('blur', function() {
                                                                                                        var $text = $(this).val().replace(/s+/g, ' ');
                                                                                                        $(this).val($text);
                                                                                                        });


                                                                                                        If this could be improved please let me know as this is the cleanest solution I could come up with.







                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered Feb 7 '17 at 2:16









                                                                                                        MatthewMatthew

                                                                                                        807519




                                                                                                        807519























                                                                                                            0














                                                                                                            Better is onvalue:



                                                                                                            <input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                                                                                            It also involves pasting, dragging and dropping, etc.






                                                                                                            share|improve this answer




























                                                                                                              0














                                                                                                              Better is onvalue:



                                                                                                              <input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                                                                                              It also involves pasting, dragging and dropping, etc.






                                                                                                              share|improve this answer


























                                                                                                                0












                                                                                                                0








                                                                                                                0







                                                                                                                Better is onvalue:



                                                                                                                <input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                                                                                                It also involves pasting, dragging and dropping, etc.






                                                                                                                share|improve this answer













                                                                                                                Better is onvalue:



                                                                                                                <input id="txt" type="text" onvalue="this.style.width = ((this.value.length + 1) * 8) + 'px';">


                                                                                                                It also involves pasting, dragging and dropping, etc.







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Apr 11 '17 at 20:03









                                                                                                                Łukasz PolowczykŁukasz Polowczyk

                                                                                                                357




                                                                                                                357























                                                                                                                    0














                                                                                                                    Why not using just css?



                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    border: 1px solid red;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }


                                                                                                                    this code was introduced by @Iain Todd to and I thought I should share it






                                                                                                                    share|improve this answer
























                                                                                                                    • It's not just css. It's just another js method. Interesting one.

                                                                                                                      – vatavale
                                                                                                                      Feb 26 '18 at 6:20
















                                                                                                                    0














                                                                                                                    Why not using just css?



                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    border: 1px solid red;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }


                                                                                                                    this code was introduced by @Iain Todd to and I thought I should share it






                                                                                                                    share|improve this answer
























                                                                                                                    • It's not just css. It's just another js method. Interesting one.

                                                                                                                      – vatavale
                                                                                                                      Feb 26 '18 at 6:20














                                                                                                                    0












                                                                                                                    0








                                                                                                                    0







                                                                                                                    Why not using just css?



                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    border: 1px solid red;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }


                                                                                                                    this code was introduced by @Iain Todd to and I thought I should share it






                                                                                                                    share|improve this answer













                                                                                                                    Why not using just css?



                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    border: 1px solid red;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }


                                                                                                                    this code was introduced by @Iain Todd to and I thought I should share it






                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>





                                                                                                                    function keyup(e) {
                                                                                                                    document.getElementById('ghost').innerText = e.target.value;
                                                                                                                    }

                                                                                                                    #wrapper {
                                                                                                                    position: relative;
                                                                                                                    min-width: 30px;
                                                                                                                    display: inline-block;
                                                                                                                    }

                                                                                                                    input {
                                                                                                                    position: absolute;
                                                                                                                    left:0;
                                                                                                                    right:0;
                                                                                                                    border:1px solid blue;
                                                                                                                    width: 100%;
                                                                                                                    }

                                                                                                                    #ghost {
                                                                                                                    color: transparent;
                                                                                                                    }

                                                                                                                    <div id="wrapper">
                                                                                                                    <input onkeyup="keyup(event)">
                                                                                                                    <div id="ghost"></div>
                                                                                                                    </div>






                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered Nov 21 '17 at 1:30









                                                                                                                    MiladMilad

                                                                                                                    13.4k33958




                                                                                                                    13.4k33958













                                                                                                                    • It's not just css. It's just another js method. Interesting one.

                                                                                                                      – vatavale
                                                                                                                      Feb 26 '18 at 6:20



















                                                                                                                    • It's not just css. It's just another js method. Interesting one.

                                                                                                                      – vatavale
                                                                                                                      Feb 26 '18 at 6:20

















                                                                                                                    It's not just css. It's just another js method. Interesting one.

                                                                                                                    – vatavale
                                                                                                                    Feb 26 '18 at 6:20





                                                                                                                    It's not just css. It's just another js method. Interesting one.

                                                                                                                    – vatavale
                                                                                                                    Feb 26 '18 at 6:20











                                                                                                                    0














                                                                                                                    This answer provides one of the most accurate methods of retrieving text width available in the browser and is more accurate than the accepted answer. It uses the canvas html5 element and unlike other answers does not add the element into the DOM and thus avoids any reflow issues caused by excessively adding elements to the DOM.



                                                                                                                    Read more about the Canvas element here in relation to text width.




                                                                                                                    NOTE: According to MDN the shorthand versions of the getPropertyValue() method such as font can be unreliable. I'd recommend getting the values singularly to improve compatibility. I only used it here for speed.







                                                                                                                    /**
                                                                                                                    * returns the width of child text of any DOM node as a float
                                                                                                                    */
                                                                                                                    function getTextWidth(el) {
                                                                                                                    // uses a cached canvas if available
                                                                                                                    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                    var context = canvas.getContext("2d");
                                                                                                                    // get the full font style property
                                                                                                                    var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                    var text = el.value;
                                                                                                                    // set the font attr for the canvas text
                                                                                                                    context.font = font;
                                                                                                                    var textMeasurement = context.measureText(text);
                                                                                                                    return textMeasurement.width;
                                                                                                                    }

                                                                                                                    var input = document.getElementById('myInput');
                                                                                                                    // listen for any input on the input field
                                                                                                                    input.addEventListener('input', function(e) {
                                                                                                                    var width = Math.floor(getTextWidth(e.target));
                                                                                                                    // add 10 px to pad the input.
                                                                                                                    var widthInPx = (width + 10) + "px";
                                                                                                                    e.target.style.width = widthInPx;
                                                                                                                    }, false);

                                                                                                                    #myInput {
                                                                                                                    font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                    min-width: 40px;
                                                                                                                    }

                                                                                                                    <input id="myInput" />








                                                                                                                    share|improve this answer




























                                                                                                                      0














                                                                                                                      This answer provides one of the most accurate methods of retrieving text width available in the browser and is more accurate than the accepted answer. It uses the canvas html5 element and unlike other answers does not add the element into the DOM and thus avoids any reflow issues caused by excessively adding elements to the DOM.



                                                                                                                      Read more about the Canvas element here in relation to text width.




                                                                                                                      NOTE: According to MDN the shorthand versions of the getPropertyValue() method such as font can be unreliable. I'd recommend getting the values singularly to improve compatibility. I only used it here for speed.







                                                                                                                      /**
                                                                                                                      * returns the width of child text of any DOM node as a float
                                                                                                                      */
                                                                                                                      function getTextWidth(el) {
                                                                                                                      // uses a cached canvas if available
                                                                                                                      var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                      var context = canvas.getContext("2d");
                                                                                                                      // get the full font style property
                                                                                                                      var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                      var text = el.value;
                                                                                                                      // set the font attr for the canvas text
                                                                                                                      context.font = font;
                                                                                                                      var textMeasurement = context.measureText(text);
                                                                                                                      return textMeasurement.width;
                                                                                                                      }

                                                                                                                      var input = document.getElementById('myInput');
                                                                                                                      // listen for any input on the input field
                                                                                                                      input.addEventListener('input', function(e) {
                                                                                                                      var width = Math.floor(getTextWidth(e.target));
                                                                                                                      // add 10 px to pad the input.
                                                                                                                      var widthInPx = (width + 10) + "px";
                                                                                                                      e.target.style.width = widthInPx;
                                                                                                                      }, false);

                                                                                                                      #myInput {
                                                                                                                      font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                      min-width: 40px;
                                                                                                                      }

                                                                                                                      <input id="myInput" />








                                                                                                                      share|improve this answer


























                                                                                                                        0












                                                                                                                        0








                                                                                                                        0







                                                                                                                        This answer provides one of the most accurate methods of retrieving text width available in the browser and is more accurate than the accepted answer. It uses the canvas html5 element and unlike other answers does not add the element into the DOM and thus avoids any reflow issues caused by excessively adding elements to the DOM.



                                                                                                                        Read more about the Canvas element here in relation to text width.




                                                                                                                        NOTE: According to MDN the shorthand versions of the getPropertyValue() method such as font can be unreliable. I'd recommend getting the values singularly to improve compatibility. I only used it here for speed.







                                                                                                                        /**
                                                                                                                        * returns the width of child text of any DOM node as a float
                                                                                                                        */
                                                                                                                        function getTextWidth(el) {
                                                                                                                        // uses a cached canvas if available
                                                                                                                        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                        var context = canvas.getContext("2d");
                                                                                                                        // get the full font style property
                                                                                                                        var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                        var text = el.value;
                                                                                                                        // set the font attr for the canvas text
                                                                                                                        context.font = font;
                                                                                                                        var textMeasurement = context.measureText(text);
                                                                                                                        return textMeasurement.width;
                                                                                                                        }

                                                                                                                        var input = document.getElementById('myInput');
                                                                                                                        // listen for any input on the input field
                                                                                                                        input.addEventListener('input', function(e) {
                                                                                                                        var width = Math.floor(getTextWidth(e.target));
                                                                                                                        // add 10 px to pad the input.
                                                                                                                        var widthInPx = (width + 10) + "px";
                                                                                                                        e.target.style.width = widthInPx;
                                                                                                                        }, false);

                                                                                                                        #myInput {
                                                                                                                        font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                        min-width: 40px;
                                                                                                                        }

                                                                                                                        <input id="myInput" />








                                                                                                                        share|improve this answer













                                                                                                                        This answer provides one of the most accurate methods of retrieving text width available in the browser and is more accurate than the accepted answer. It uses the canvas html5 element and unlike other answers does not add the element into the DOM and thus avoids any reflow issues caused by excessively adding elements to the DOM.



                                                                                                                        Read more about the Canvas element here in relation to text width.




                                                                                                                        NOTE: According to MDN the shorthand versions of the getPropertyValue() method such as font can be unreliable. I'd recommend getting the values singularly to improve compatibility. I only used it here for speed.







                                                                                                                        /**
                                                                                                                        * returns the width of child text of any DOM node as a float
                                                                                                                        */
                                                                                                                        function getTextWidth(el) {
                                                                                                                        // uses a cached canvas if available
                                                                                                                        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                        var context = canvas.getContext("2d");
                                                                                                                        // get the full font style property
                                                                                                                        var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                        var text = el.value;
                                                                                                                        // set the font attr for the canvas text
                                                                                                                        context.font = font;
                                                                                                                        var textMeasurement = context.measureText(text);
                                                                                                                        return textMeasurement.width;
                                                                                                                        }

                                                                                                                        var input = document.getElementById('myInput');
                                                                                                                        // listen for any input on the input field
                                                                                                                        input.addEventListener('input', function(e) {
                                                                                                                        var width = Math.floor(getTextWidth(e.target));
                                                                                                                        // add 10 px to pad the input.
                                                                                                                        var widthInPx = (width + 10) + "px";
                                                                                                                        e.target.style.width = widthInPx;
                                                                                                                        }, false);

                                                                                                                        #myInput {
                                                                                                                        font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                        min-width: 40px;
                                                                                                                        }

                                                                                                                        <input id="myInput" />








                                                                                                                        /**
                                                                                                                        * returns the width of child text of any DOM node as a float
                                                                                                                        */
                                                                                                                        function getTextWidth(el) {
                                                                                                                        // uses a cached canvas if available
                                                                                                                        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                        var context = canvas.getContext("2d");
                                                                                                                        // get the full font style property
                                                                                                                        var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                        var text = el.value;
                                                                                                                        // set the font attr for the canvas text
                                                                                                                        context.font = font;
                                                                                                                        var textMeasurement = context.measureText(text);
                                                                                                                        return textMeasurement.width;
                                                                                                                        }

                                                                                                                        var input = document.getElementById('myInput');
                                                                                                                        // listen for any input on the input field
                                                                                                                        input.addEventListener('input', function(e) {
                                                                                                                        var width = Math.floor(getTextWidth(e.target));
                                                                                                                        // add 10 px to pad the input.
                                                                                                                        var widthInPx = (width + 10) + "px";
                                                                                                                        e.target.style.width = widthInPx;
                                                                                                                        }, false);

                                                                                                                        #myInput {
                                                                                                                        font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                        min-width: 40px;
                                                                                                                        }

                                                                                                                        <input id="myInput" />





                                                                                                                        /**
                                                                                                                        * returns the width of child text of any DOM node as a float
                                                                                                                        */
                                                                                                                        function getTextWidth(el) {
                                                                                                                        // uses a cached canvas if available
                                                                                                                        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
                                                                                                                        var context = canvas.getContext("2d");
                                                                                                                        // get the full font style property
                                                                                                                        var font = window.getComputedStyle(el, null).getPropertyValue('font');
                                                                                                                        var text = el.value;
                                                                                                                        // set the font attr for the canvas text
                                                                                                                        context.font = font;
                                                                                                                        var textMeasurement = context.measureText(text);
                                                                                                                        return textMeasurement.width;
                                                                                                                        }

                                                                                                                        var input = document.getElementById('myInput');
                                                                                                                        // listen for any input on the input field
                                                                                                                        input.addEventListener('input', function(e) {
                                                                                                                        var width = Math.floor(getTextWidth(e.target));
                                                                                                                        // add 10 px to pad the input.
                                                                                                                        var widthInPx = (width + 10) + "px";
                                                                                                                        e.target.style.width = widthInPx;
                                                                                                                        }, false);

                                                                                                                        #myInput {
                                                                                                                        font: normal normal 400 normal 18px / normal Roboto, sans-serif;
                                                                                                                        min-width: 40px;
                                                                                                                        }

                                                                                                                        <input id="myInput" />






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered May 16 '18 at 0:07









                                                                                                                        Matthew BrentMatthew Brent

                                                                                                                        784518




                                                                                                                        784518























                                                                                                                            0














                                                                                                                            A bullet-proof, generic way has to:




                                                                                                                            1. Take into account all possible styles of the measured input element

                                                                                                                            2. Be able to apply the measurement on any input without modifying the HTML or


                                                                                                                            Codepen demo






                                                                                                                            var getInputValueWidth = (function(){
                                                                                                                            // https://stackoverflow.com/a/49982135/104380
                                                                                                                            function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                            var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                            Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                            }

                                                                                                                            function createInputMeassureElm( inputelm ){
                                                                                                                            // create a dummy input element for measurements
                                                                                                                            var meassureElm = document.createElement('span');
                                                                                                                            // copy the read input's styles to the dummy input
                                                                                                                            copyNodeStyle(inputelm, meassureElm);

                                                                                                                            // set hard-coded styles needed for propper meassuring
                                                                                                                            meassureElm.style.width = 'auto';
                                                                                                                            meassureElm.style.position = 'absolute';
                                                                                                                            meassureElm.style.left = '-9999px';
                                                                                                                            meassureElm.style.top = '-9999px';
                                                                                                                            meassureElm.style.whiteSpace = 'pre';

                                                                                                                            meassureElm.textContent = inputelm.value || '';

                                                                                                                            // add the meassure element to the body
                                                                                                                            document.body.appendChild(meassureElm);

                                                                                                                            return meassureElm;
                                                                                                                            }

                                                                                                                            return function(){
                                                                                                                            return createInputMeassureElm(this).offsetWidth;
                                                                                                                            }
                                                                                                                            })();


                                                                                                                            // delegated event binding
                                                                                                                            document.body.addEventListener('input', onInputDelegate)

                                                                                                                            function onInputDelegate(e){
                                                                                                                            if( e.target.classList.contains('autoSize') )
                                                                                                                            e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                            }

                                                                                                                            input{ 
                                                                                                                            font-size:1.3em;
                                                                                                                            padding:5px;
                                                                                                                            margin-bottom: 1em;
                                                                                                                            }

                                                                                                                            input.type2{
                                                                                                                            font-size: 2.5em;
                                                                                                                            letter-spacing: 4px;
                                                                                                                            font-style: italic;
                                                                                                                            }

                                                                                                                            <input class='autoSize' value="type something">
                                                                                                                            <br>
                                                                                                                            <input class='autoSize type2' value="here too">








                                                                                                                            share|improve this answer




























                                                                                                                              0














                                                                                                                              A bullet-proof, generic way has to:




                                                                                                                              1. Take into account all possible styles of the measured input element

                                                                                                                              2. Be able to apply the measurement on any input without modifying the HTML or


                                                                                                                              Codepen demo






                                                                                                                              var getInputValueWidth = (function(){
                                                                                                                              // https://stackoverflow.com/a/49982135/104380
                                                                                                                              function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                              var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                              Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                              }

                                                                                                                              function createInputMeassureElm( inputelm ){
                                                                                                                              // create a dummy input element for measurements
                                                                                                                              var meassureElm = document.createElement('span');
                                                                                                                              // copy the read input's styles to the dummy input
                                                                                                                              copyNodeStyle(inputelm, meassureElm);

                                                                                                                              // set hard-coded styles needed for propper meassuring
                                                                                                                              meassureElm.style.width = 'auto';
                                                                                                                              meassureElm.style.position = 'absolute';
                                                                                                                              meassureElm.style.left = '-9999px';
                                                                                                                              meassureElm.style.top = '-9999px';
                                                                                                                              meassureElm.style.whiteSpace = 'pre';

                                                                                                                              meassureElm.textContent = inputelm.value || '';

                                                                                                                              // add the meassure element to the body
                                                                                                                              document.body.appendChild(meassureElm);

                                                                                                                              return meassureElm;
                                                                                                                              }

                                                                                                                              return function(){
                                                                                                                              return createInputMeassureElm(this).offsetWidth;
                                                                                                                              }
                                                                                                                              })();


                                                                                                                              // delegated event binding
                                                                                                                              document.body.addEventListener('input', onInputDelegate)

                                                                                                                              function onInputDelegate(e){
                                                                                                                              if( e.target.classList.contains('autoSize') )
                                                                                                                              e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                              }

                                                                                                                              input{ 
                                                                                                                              font-size:1.3em;
                                                                                                                              padding:5px;
                                                                                                                              margin-bottom: 1em;
                                                                                                                              }

                                                                                                                              input.type2{
                                                                                                                              font-size: 2.5em;
                                                                                                                              letter-spacing: 4px;
                                                                                                                              font-style: italic;
                                                                                                                              }

                                                                                                                              <input class='autoSize' value="type something">
                                                                                                                              <br>
                                                                                                                              <input class='autoSize type2' value="here too">








                                                                                                                              share|improve this answer


























                                                                                                                                0












                                                                                                                                0








                                                                                                                                0







                                                                                                                                A bullet-proof, generic way has to:




                                                                                                                                1. Take into account all possible styles of the measured input element

                                                                                                                                2. Be able to apply the measurement on any input without modifying the HTML or


                                                                                                                                Codepen demo






                                                                                                                                var getInputValueWidth = (function(){
                                                                                                                                // https://stackoverflow.com/a/49982135/104380
                                                                                                                                function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                                var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                                Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                                }

                                                                                                                                function createInputMeassureElm( inputelm ){
                                                                                                                                // create a dummy input element for measurements
                                                                                                                                var meassureElm = document.createElement('span');
                                                                                                                                // copy the read input's styles to the dummy input
                                                                                                                                copyNodeStyle(inputelm, meassureElm);

                                                                                                                                // set hard-coded styles needed for propper meassuring
                                                                                                                                meassureElm.style.width = 'auto';
                                                                                                                                meassureElm.style.position = 'absolute';
                                                                                                                                meassureElm.style.left = '-9999px';
                                                                                                                                meassureElm.style.top = '-9999px';
                                                                                                                                meassureElm.style.whiteSpace = 'pre';

                                                                                                                                meassureElm.textContent = inputelm.value || '';

                                                                                                                                // add the meassure element to the body
                                                                                                                                document.body.appendChild(meassureElm);

                                                                                                                                return meassureElm;
                                                                                                                                }

                                                                                                                                return function(){
                                                                                                                                return createInputMeassureElm(this).offsetWidth;
                                                                                                                                }
                                                                                                                                })();


                                                                                                                                // delegated event binding
                                                                                                                                document.body.addEventListener('input', onInputDelegate)

                                                                                                                                function onInputDelegate(e){
                                                                                                                                if( e.target.classList.contains('autoSize') )
                                                                                                                                e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                                }

                                                                                                                                input{ 
                                                                                                                                font-size:1.3em;
                                                                                                                                padding:5px;
                                                                                                                                margin-bottom: 1em;
                                                                                                                                }

                                                                                                                                input.type2{
                                                                                                                                font-size: 2.5em;
                                                                                                                                letter-spacing: 4px;
                                                                                                                                font-style: italic;
                                                                                                                                }

                                                                                                                                <input class='autoSize' value="type something">
                                                                                                                                <br>
                                                                                                                                <input class='autoSize type2' value="here too">








                                                                                                                                share|improve this answer













                                                                                                                                A bullet-proof, generic way has to:




                                                                                                                                1. Take into account all possible styles of the measured input element

                                                                                                                                2. Be able to apply the measurement on any input without modifying the HTML or


                                                                                                                                Codepen demo






                                                                                                                                var getInputValueWidth = (function(){
                                                                                                                                // https://stackoverflow.com/a/49982135/104380
                                                                                                                                function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                                var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                                Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                                }

                                                                                                                                function createInputMeassureElm( inputelm ){
                                                                                                                                // create a dummy input element for measurements
                                                                                                                                var meassureElm = document.createElement('span');
                                                                                                                                // copy the read input's styles to the dummy input
                                                                                                                                copyNodeStyle(inputelm, meassureElm);

                                                                                                                                // set hard-coded styles needed for propper meassuring
                                                                                                                                meassureElm.style.width = 'auto';
                                                                                                                                meassureElm.style.position = 'absolute';
                                                                                                                                meassureElm.style.left = '-9999px';
                                                                                                                                meassureElm.style.top = '-9999px';
                                                                                                                                meassureElm.style.whiteSpace = 'pre';

                                                                                                                                meassureElm.textContent = inputelm.value || '';

                                                                                                                                // add the meassure element to the body
                                                                                                                                document.body.appendChild(meassureElm);

                                                                                                                                return meassureElm;
                                                                                                                                }

                                                                                                                                return function(){
                                                                                                                                return createInputMeassureElm(this).offsetWidth;
                                                                                                                                }
                                                                                                                                })();


                                                                                                                                // delegated event binding
                                                                                                                                document.body.addEventListener('input', onInputDelegate)

                                                                                                                                function onInputDelegate(e){
                                                                                                                                if( e.target.classList.contains('autoSize') )
                                                                                                                                e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                                }

                                                                                                                                input{ 
                                                                                                                                font-size:1.3em;
                                                                                                                                padding:5px;
                                                                                                                                margin-bottom: 1em;
                                                                                                                                }

                                                                                                                                input.type2{
                                                                                                                                font-size: 2.5em;
                                                                                                                                letter-spacing: 4px;
                                                                                                                                font-style: italic;
                                                                                                                                }

                                                                                                                                <input class='autoSize' value="type something">
                                                                                                                                <br>
                                                                                                                                <input class='autoSize type2' value="here too">








                                                                                                                                var getInputValueWidth = (function(){
                                                                                                                                // https://stackoverflow.com/a/49982135/104380
                                                                                                                                function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                                var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                                Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                                }

                                                                                                                                function createInputMeassureElm( inputelm ){
                                                                                                                                // create a dummy input element for measurements
                                                                                                                                var meassureElm = document.createElement('span');
                                                                                                                                // copy the read input's styles to the dummy input
                                                                                                                                copyNodeStyle(inputelm, meassureElm);

                                                                                                                                // set hard-coded styles needed for propper meassuring
                                                                                                                                meassureElm.style.width = 'auto';
                                                                                                                                meassureElm.style.position = 'absolute';
                                                                                                                                meassureElm.style.left = '-9999px';
                                                                                                                                meassureElm.style.top = '-9999px';
                                                                                                                                meassureElm.style.whiteSpace = 'pre';

                                                                                                                                meassureElm.textContent = inputelm.value || '';

                                                                                                                                // add the meassure element to the body
                                                                                                                                document.body.appendChild(meassureElm);

                                                                                                                                return meassureElm;
                                                                                                                                }

                                                                                                                                return function(){
                                                                                                                                return createInputMeassureElm(this).offsetWidth;
                                                                                                                                }
                                                                                                                                })();


                                                                                                                                // delegated event binding
                                                                                                                                document.body.addEventListener('input', onInputDelegate)

                                                                                                                                function onInputDelegate(e){
                                                                                                                                if( e.target.classList.contains('autoSize') )
                                                                                                                                e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                                }

                                                                                                                                input{ 
                                                                                                                                font-size:1.3em;
                                                                                                                                padding:5px;
                                                                                                                                margin-bottom: 1em;
                                                                                                                                }

                                                                                                                                input.type2{
                                                                                                                                font-size: 2.5em;
                                                                                                                                letter-spacing: 4px;
                                                                                                                                font-style: italic;
                                                                                                                                }

                                                                                                                                <input class='autoSize' value="type something">
                                                                                                                                <br>
                                                                                                                                <input class='autoSize type2' value="here too">





                                                                                                                                var getInputValueWidth = (function(){
                                                                                                                                // https://stackoverflow.com/a/49982135/104380
                                                                                                                                function copyNodeStyle(sourceNode, targetNode) {
                                                                                                                                var computedStyle = window.getComputedStyle(sourceNode);
                                                                                                                                Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
                                                                                                                                }

                                                                                                                                function createInputMeassureElm( inputelm ){
                                                                                                                                // create a dummy input element for measurements
                                                                                                                                var meassureElm = document.createElement('span');
                                                                                                                                // copy the read input's styles to the dummy input
                                                                                                                                copyNodeStyle(inputelm, meassureElm);

                                                                                                                                // set hard-coded styles needed for propper meassuring
                                                                                                                                meassureElm.style.width = 'auto';
                                                                                                                                meassureElm.style.position = 'absolute';
                                                                                                                                meassureElm.style.left = '-9999px';
                                                                                                                                meassureElm.style.top = '-9999px';
                                                                                                                                meassureElm.style.whiteSpace = 'pre';

                                                                                                                                meassureElm.textContent = inputelm.value || '';

                                                                                                                                // add the meassure element to the body
                                                                                                                                document.body.appendChild(meassureElm);

                                                                                                                                return meassureElm;
                                                                                                                                }

                                                                                                                                return function(){
                                                                                                                                return createInputMeassureElm(this).offsetWidth;
                                                                                                                                }
                                                                                                                                })();


                                                                                                                                // delegated event binding
                                                                                                                                document.body.addEventListener('input', onInputDelegate)

                                                                                                                                function onInputDelegate(e){
                                                                                                                                if( e.target.classList.contains('autoSize') )
                                                                                                                                e.target.style.width = getInputValueWidth.call(e.target) + 'px';
                                                                                                                                }

                                                                                                                                input{ 
                                                                                                                                font-size:1.3em;
                                                                                                                                padding:5px;
                                                                                                                                margin-bottom: 1em;
                                                                                                                                }

                                                                                                                                input.type2{
                                                                                                                                font-size: 2.5em;
                                                                                                                                letter-spacing: 4px;
                                                                                                                                font-style: italic;
                                                                                                                                }

                                                                                                                                <input class='autoSize' value="type something">
                                                                                                                                <br>
                                                                                                                                <input class='autoSize type2' value="here too">






                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered May 16 '18 at 11:46









                                                                                                                                vsyncvsync

                                                                                                                                46.6k36159220




                                                                                                                                46.6k36159220























                                                                                                                                    0














                                                                                                                                    Here is my 2 cents.
                                                                                                                                    Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.






                                                                                                                                    $(".answers_number").keyup(function(){
                                                                                                                                    $( "#number_box" ).html( $( this ).val() );
                                                                                                                                    $( this ).animate({
                                                                                                                                    width: $( "#number_box" ).width()+20
                                                                                                                                    }, 300, function() {
                                                                                                                                    });
                                                                                                                                    });

                                                                                                                                    #number_box {
                                                                                                                                    position: absolute;
                                                                                                                                    visibility: hidden;
                                                                                                                                    height: auto;
                                                                                                                                    width: auto;
                                                                                                                                    white-space: nowrap;
                                                                                                                                    padding:0 4px;
                                                                                                                                    /*Your font styles to match input*/
                                                                                                                                    font-family:Arial;
                                                                                                                                    font-size: 30px;
                                                                                                                                    }

                                                                                                                                    .answers_number {
                                                                                                                                    font-size: 30px;
                                                                                                                                    font-family:Arial;
                                                                                                                                    }

                                                                                                                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                    <input type="number" class="answers_number" />
                                                                                                                                    <div id="number_box">
                                                                                                                                    </div>








                                                                                                                                    share|improve this answer






























                                                                                                                                      0














                                                                                                                                      Here is my 2 cents.
                                                                                                                                      Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.






                                                                                                                                      $(".answers_number").keyup(function(){
                                                                                                                                      $( "#number_box" ).html( $( this ).val() );
                                                                                                                                      $( this ).animate({
                                                                                                                                      width: $( "#number_box" ).width()+20
                                                                                                                                      }, 300, function() {
                                                                                                                                      });
                                                                                                                                      });

                                                                                                                                      #number_box {
                                                                                                                                      position: absolute;
                                                                                                                                      visibility: hidden;
                                                                                                                                      height: auto;
                                                                                                                                      width: auto;
                                                                                                                                      white-space: nowrap;
                                                                                                                                      padding:0 4px;
                                                                                                                                      /*Your font styles to match input*/
                                                                                                                                      font-family:Arial;
                                                                                                                                      font-size: 30px;
                                                                                                                                      }

                                                                                                                                      .answers_number {
                                                                                                                                      font-size: 30px;
                                                                                                                                      font-family:Arial;
                                                                                                                                      }

                                                                                                                                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                      <input type="number" class="answers_number" />
                                                                                                                                      <div id="number_box">
                                                                                                                                      </div>








                                                                                                                                      share|improve this answer




























                                                                                                                                        0












                                                                                                                                        0








                                                                                                                                        0







                                                                                                                                        Here is my 2 cents.
                                                                                                                                        Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.






                                                                                                                                        $(".answers_number").keyup(function(){
                                                                                                                                        $( "#number_box" ).html( $( this ).val() );
                                                                                                                                        $( this ).animate({
                                                                                                                                        width: $( "#number_box" ).width()+20
                                                                                                                                        }, 300, function() {
                                                                                                                                        });
                                                                                                                                        });

                                                                                                                                        #number_box {
                                                                                                                                        position: absolute;
                                                                                                                                        visibility: hidden;
                                                                                                                                        height: auto;
                                                                                                                                        width: auto;
                                                                                                                                        white-space: nowrap;
                                                                                                                                        padding:0 4px;
                                                                                                                                        /*Your font styles to match input*/
                                                                                                                                        font-family:Arial;
                                                                                                                                        font-size: 30px;
                                                                                                                                        }

                                                                                                                                        .answers_number {
                                                                                                                                        font-size: 30px;
                                                                                                                                        font-family:Arial;
                                                                                                                                        }

                                                                                                                                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                        <input type="number" class="answers_number" />
                                                                                                                                        <div id="number_box">
                                                                                                                                        </div>








                                                                                                                                        share|improve this answer















                                                                                                                                        Here is my 2 cents.
                                                                                                                                        Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.






                                                                                                                                        $(".answers_number").keyup(function(){
                                                                                                                                        $( "#number_box" ).html( $( this ).val() );
                                                                                                                                        $( this ).animate({
                                                                                                                                        width: $( "#number_box" ).width()+20
                                                                                                                                        }, 300, function() {
                                                                                                                                        });
                                                                                                                                        });

                                                                                                                                        #number_box {
                                                                                                                                        position: absolute;
                                                                                                                                        visibility: hidden;
                                                                                                                                        height: auto;
                                                                                                                                        width: auto;
                                                                                                                                        white-space: nowrap;
                                                                                                                                        padding:0 4px;
                                                                                                                                        /*Your font styles to match input*/
                                                                                                                                        font-family:Arial;
                                                                                                                                        font-size: 30px;
                                                                                                                                        }

                                                                                                                                        .answers_number {
                                                                                                                                        font-size: 30px;
                                                                                                                                        font-family:Arial;
                                                                                                                                        }

                                                                                                                                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                        <input type="number" class="answers_number" />
                                                                                                                                        <div id="number_box">
                                                                                                                                        </div>








                                                                                                                                        $(".answers_number").keyup(function(){
                                                                                                                                        $( "#number_box" ).html( $( this ).val() );
                                                                                                                                        $( this ).animate({
                                                                                                                                        width: $( "#number_box" ).width()+20
                                                                                                                                        }, 300, function() {
                                                                                                                                        });
                                                                                                                                        });

                                                                                                                                        #number_box {
                                                                                                                                        position: absolute;
                                                                                                                                        visibility: hidden;
                                                                                                                                        height: auto;
                                                                                                                                        width: auto;
                                                                                                                                        white-space: nowrap;
                                                                                                                                        padding:0 4px;
                                                                                                                                        /*Your font styles to match input*/
                                                                                                                                        font-family:Arial;
                                                                                                                                        font-size: 30px;
                                                                                                                                        }

                                                                                                                                        .answers_number {
                                                                                                                                        font-size: 30px;
                                                                                                                                        font-family:Arial;
                                                                                                                                        }

                                                                                                                                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                        <input type="number" class="answers_number" />
                                                                                                                                        <div id="number_box">
                                                                                                                                        </div>





                                                                                                                                        $(".answers_number").keyup(function(){
                                                                                                                                        $( "#number_box" ).html( $( this ).val() );
                                                                                                                                        $( this ).animate({
                                                                                                                                        width: $( "#number_box" ).width()+20
                                                                                                                                        }, 300, function() {
                                                                                                                                        });
                                                                                                                                        });

                                                                                                                                        #number_box {
                                                                                                                                        position: absolute;
                                                                                                                                        visibility: hidden;
                                                                                                                                        height: auto;
                                                                                                                                        width: auto;
                                                                                                                                        white-space: nowrap;
                                                                                                                                        padding:0 4px;
                                                                                                                                        /*Your font styles to match input*/
                                                                                                                                        font-family:Arial;
                                                                                                                                        font-size: 30px;
                                                                                                                                        }

                                                                                                                                        .answers_number {
                                                                                                                                        font-size: 30px;
                                                                                                                                        font-family:Arial;
                                                                                                                                        }

                                                                                                                                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                                                                                                                                        <input type="number" class="answers_number" />
                                                                                                                                        <div id="number_box">
                                                                                                                                        </div>






                                                                                                                                        share|improve this answer














                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer








                                                                                                                                        edited Nov 21 '18 at 0:51

























                                                                                                                                        answered Nov 21 '18 at 0:19









                                                                                                                                        Thomas ByyThomas Byy

                                                                                                                                        1,0191012




                                                                                                                                        1,0191012






























                                                                                                                                            draft saved

                                                                                                                                            draft discarded




















































                                                                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                            But avoid



                                                                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                            To learn more, see our tips on writing great answers.




                                                                                                                                            draft saved


                                                                                                                                            draft discarded














                                                                                                                                            StackExchange.ready(
                                                                                                                                            function () {
                                                                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3392493%2fadjust-width-of-input-field-to-its-input%23new-answer', 'question_page');
                                                                                                                                            }
                                                                                                                                            );

                                                                                                                                            Post as a guest















                                                                                                                                            Required, but never shown





















































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown

































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown







                                                                                                                                            Popular posts from this blog

                                                                                                                                            MongoDB - Not Authorized To Execute Command

                                                                                                                                            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                                                                                                                            How to fix TextFormField cause rebuild widget in Flutter