faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 19 people (95%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How am I able to stop entering text into a text area when a certain limit is reached?

Apr 5th, 2008 19:21
ha mo, Darton Williams, john pay,


Use onKeyPress or onKeyDown to monitor the length:
<HEAD>
<SCRIPT language="JavaScript">
function checkLength()
{
if(document.myForm.text1.value.length >= 10)
	{
	return false;
	}
}
function validateForm()
{
if(document.myForm.text1.value.length > 10)
	{
	alert('Too many characters');
	return false;
	}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="myForm" action="#" onSubmit="return validateForm()">
<TEXTAREA name="text1" onKeyPress="return checkLength()"></TEXTAREA><BR>
<input type="submit">
</FORM>
</BODY>
So we have two things going on here: 
First, we're looking at the length with each keystroke to make sure the 
max length hasn't been reached. Then, if somebody decides to get goofy 
and paste a bunch of text into the field, the form still won't submit 
if our max length is exceeded. This works in both Netscape and IE.
The only problem here is that in a real-world situation, you'd have to 
add some checks for the backspace and possibly arrow and delete keys, 
because once this textarea gets 10 characters, you can't delete 
anything (other than by selecting and cutting). This type of checking 
can be a real pain in Netscape...
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com