Iwasakabukiman
Iwasakabukiman

Reputation: 1453

Character Limit in HTML

How do you impose a character limit on a text input in HTML?

Upvotes: 96

Views: 185523

Answers (6)

shekh danishuesn
shekh danishuesn

Reputation: 21

you can set maxlength with jquery which is very fast

jQuery(document).ready(function($){ //fire on DOM ready
 setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})

Upvotes: 0

Bite code
Bite code

Reputation: 596853

There are 2 main 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.

Upvotes: 134

nickf
nickf

Reputation: 546085

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: How to impose maxlength on textArea in HTML using JavaScript

Upvotes: 5

pilsetnieks
pilsetnieks

Reputation: 10420

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.

Upvotes: 1

Devin Jeanpierre
Devin Jeanpierre

Reputation: 95556

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. ;)

Upvotes: 12

cruizer
cruizer

Reputation: 6151

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />

Upvotes: 44

Related Questions