2 Replies Latest reply on Apr 3, 2009 4:36 AM by alexstuckey

    Javascript - text input size

    alexstuckey
      I'm trying to make a text input's size/ length change when the value is changed and made to fit the value.

      I tried:

      var obj_txt_box = document.getElementById("txt_box");
      obj_txt_box.size = obj_txt_box.value.length;

      But it doesn't work.

      Thank You.
        • 1. Re: Javascript - text input size
          Jeff Swartz Level 3
          The re-rendering only seems to work if you also adjust some CSS properties, as in the following:

          <html>
          <head>
          <style>
          input { font-family:Arial; font-size:12px; }
          </style>
          <link href="sample.css" rel="stylesheet" type="text/css">
          <script type="text/javascript" src="AIRAliases.js"></script>
          <script type="text/javascript">
          function resizeTB()
          {
          var styleSheet = document.styleSheets[0];
          styleSheet.cssRules[0].style.color = "#000000";
          var obj_txt_box = document.getElementById("txt_box");
          obj_txt_box.size = obj_txt_box.value.length;
          }
          </script>
          </head>
          <body onLoad="resizeTB()">
          <input type="text" id="txt_box" value="foo bar" onKeyDown="resizeTB()"/>
          </body>
          </html>

          Note that the line that sets styleSheet.cssRules[0].style.color does not change the font color. But if you comment out that line, the obj_txt_box.size setting does not work.
          • 2. Re: Javascript - text input size
            alexstuckey Level 1
            Thank you for the answer. It worked straight away! It's so annoying when you can't find the answer to something.