How to Set the Textbox Width in JavaScript

Updated July 18, 2017

The JavaScript language allows programmers to inspect and modify the internal structure of a Web document. JavaScript has methods to access the application programming interface of HTML (Hypertext Markup Language) known as the Document Object Model, or DOM. The JavaScript method getElementById() allows the programmer to change HTML tag styling properties such as backgrounds, fonts, borders, widths and positioning. The HTML tag must be labelled with an ID so the getElementById() method can find and access it. The width of an HTML form text box can be altered by using the JavaScript DOM getElementByI() method as well.

Launch the standard plain-text text editor application that is available on your computer.

Enter the following code into the text editor:

First name:

Last name:

Click here to change Textbox width

Click the "File" menu. Select the "Save" option. Save under the file name "test.html."

Launch the Web browser that is available on your computer. Click on the "File" menu item and select "Open File."

Locate the file "test.html" just created, select it with the mouse then click on "Open."

Click on the text within the grey background with the mouse to change the form text box's width.


Rather than set the text box width to a specific, absolute size, you can change it relative to its current width. Get the current width of the text box using the getElementById() method. Add the additional width to this value. Set the new width of the text box using the getElementById() method again. To see an example of this, substitute the following code for the JavaScript function change Width(): <script language="javascript"> function change Width(){ / gets a pointer to the texbox labelled firsttextbox / var firstbox=document.getElementById("firsttextbox"); / get the current width from this object / var; / add 60 ems to the current width at set it to the fisttextbox /"60em"; document.getElementById("secondtextbox").style.width = "40em"; document.getElementById("mybutton").innerHTML = "Works! 1st box is 60 extra ems and 2nd box 40ems absolute"; } </script>


The major Web browsers will display valid HTML and CSS code differently. Even different versions of the same browser may produce unexpected display issues. Always test your code on different browsers and older versions of the same browser in order to ensure the code works as expected.

bibliography-icon icon for annotation tool Cite this Article

About the Author

Allen Bethea has written articles on programming, web design,operating systems and computer hardware since 2002. He holds a Bachelor of Science from UNC-Chapel Hill and AAS degrees in office technology, mechanical engineering/drafting and internet technology. Allen has extensive experience with desktop and system software for both Windows and Linux operating systems.