Home | Php | JavaScript | SQL | HTML | Server Admin | Tools

Change Cell Color on Mouseover
Change Background Color
Break out of Frames
Change Cursor
Limit Input Text
Get Object By ID
Up/Down Buttons (Spinner)
Other sites
Image Editor
Top 10 web hosting reviews

Limiting input text in a form

So you have a submission form for this that or the other thing and you want to limit the amount of text the user can type in a certain field. This can be very useful, for example if you're only going to use the first 200 characters of your "description" field, why let the user think they can put in more text? Also, if you state that only 200 characters can be entered, it's a nice touch to let the user know how many character they've entered, and how many they have left. Ok, convinced of it's usefulness? Let's get down to business.

Your HTML form

You'll have to add an "onKeyUp" attribute to the form input element (or textarea) that you want to control the input for. Here's the code for the HTML page, including the onKeyUp attribute.

Example Code
<textarea cols=100 rows=20 onkeyup="change(this);"></textarea>
<br>You've typed <span id="char_cnt">0</span> character(s). You
are allowed <span id="chars_left">lots</span> more.

The JavaScript to make this happen

Add this function between the <head> tags for the page you want to use this on.

Example Code
<script type="text/javascript">
function change (el) {
var max_len = 10;
if (el.value.length > max_len) {
el.value = el.value.substr(0, max_len);
document.getElementById('char_cnt').innerHTML = el.value.length;
document.getElementById('chars_left').innerHTML = max_len - el.value.length;
return true;


Here's a working example of how this works. It is currently limiting input to 100 characters, so you don't have to type so much to see how it works.

In this example, we used a textarea, but it will work the same if you want to use it with an input field of type text. Hope this helped ya!.

Start typing here.

You've typed 0 character(s). You are allowed lots more.

Enjoy, and if you use this code on your website, feel free to let me know, at tech AT webcodingtech DOT com and, if you're feeling downright generous, go ahead and add a link back to this page, saying where you got your inspiration from

Link back to this page

Copy and paste this HTML code into your page to link back to this very page:

Or just link to the WebCodingTech site:

And your link will look like this:
      Inspired by stuff found at www.webcodingtech.com.


Copyright © 2005 WebCodingTech.com Our URL is: http://www.webcodingtech.com