Is it OK to have maxlength as the only length definition of an input type="text"? Will all browsers make sure the entire length is visible?
| SitePoint Sponsor |

Is it OK to have maxlength as the only length definition of an input type="text"? Will all browsers make sure the entire length is visible?


The maxlength attribute only specifies how many characters a user should be able to type in a field. It says nothing about the visible size of the element. Note that browsers may or may not respect the maxlength setting, so you still need to validate it server-side. (And nefarious scripts, of course, will definitely not bother.)
The visible width of input fields should be specified in CSS (preferably in em units, so that it adapts when the user changes the text size).
Birnam wood is come to Dunsinane

OK, thank you. If I have maxlength="10" and font-size:1em, should width:10em keep the entire field visible across browsers?

Since characters in most fonts vary in width the number of characters that will be visible will depend on what characters are entered. iiiiiiiiii takes up less width than MMMM even though it contains 2-1/2 times as many characters.
Stephen J Chapman
javascriptexample.net, Book Reviews, follow me on Twitter
HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
<input name="html5" type="text" required pattern="^$">

But there aren't any fonts that are wider than they are tall, right? em refers to the height of the font, right? It seems like 10em would cover maxlength="10" and font-size:1em in all situations.

Stephen J Chapman
javascriptexample.net, Book Reviews, follow me on Twitter
HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
<input name="html5" type="text" required pattern="^$">


I usually divide the number of characters by 2, rounding up if necessary, to get a suitable value in em. So for a 10-character field I'd probably use width:5em or so.
But you are right: if you set the width to 10em you're virtually guaranteed that even ten W's will fit.
Birnam wood is come to Dunsinane

Thanks guys. AutisticCuckoo, I just tried your method of determining width and the field ended up being 25% too short on Firefox-3.0.11 on Linux. The characters I used were all numbers. Just thought I'd let you know.


Yeah, it's a rule of thumb only. For numeric fields I usually add one or two units, so that a ten-digit field gets width:6em or width:7em. It depends a bit on which font you use, too.
Birnam wood is come to Dunsinane
Bookmarks