views:

5695

answers:

5

How do you impliment a character limit on a textbox in HTML? I know it's a basic question, but I don't really use HTML too much, so I don't know.

+16  A: 

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />
cruizer
This is true, but some clients don't check this. This is especcially true for mobile phone based clients.
Drejc
There are also ways to remove them. For example the Firefox Web Developer Extension has a Remove Maximum lengths function.
Sam Hasler
+2  A: 

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: http://www.quirksmode.org/dom/maxlength.html

nickf
+5  A: 

In addition to the above, I would like to point out that client-side validation (HTML code, javascript, etc.) is never enough. Also check the length server-side, or just don't check at all (if it's not so important that people can be allowed to get around it, then it's not important enough to really warrant any steps to prevent that, either).

Also, fellows, he (or she) said HTML, not XHTML. ;)

Devin Jeanpierre
i agree. one can POST data directly into a web site using some scripting tool, so in that case maxlength and other browser-side validations are not foolproof
cruizer
or use firebug and remove the maxlength attribute.
Zach
A: 

For the <input> element there's the maxlength attribute:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

(by the way, the type is "text", not "textbox" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.

Nouveau
+3  A: 

There are 2 mains solutions :

The pure HTML one :

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

The javascript one (attach it to a onKey Event) :

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.

e-satis
Check on the server as a final sanity check, but add client-side enhancement if you can do so; it makes for a richer user experience.
Rob
Sure, more work, but definitely the best way to go.
e-satis