felonious
07-11-2005, 07:00 PM
Hi everyone,
I know this is a somewhat common task, but I'm having problems with my implementation. I'm trying to write code that limits a textarea to a certain number of characters (in my case, 250). I want to do this interactively, where the user cannot type anything over 250 characters. I'm not too concerned about cut&paste at this point, though I might update the script later if it becomes a common issue.
Anyway, here's what I have for code. Any suggestions are appreciated! :)
<html>
<head>
<title>Test</title>
<script language="JavaScript" type="text/javascript">
// set up allowable characters
var reg = /(\x46|\x08|\x09)/; // backspace, delete & tab chars
// function to limit textarea to 250 characters
function ca(e) {
// set up variables
var key;
var area;
if (window.event) {
// IE
key = e.keyCode;
area = e.srcElement;
} else if (e.which) {
// netscape
key = e.which;
area = e.target;
} else {
// no event, so pass through
return true;
}
// if the length is under 250 or it's a delete, space, or tab, allow it
// otherwise, disallow
if (area.value.length < 250 || reg.test( String.fromCharCode(key)) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<form name="form1">
<textarea name="thearea"
rows="5"
cols="30"
onKeyUp="listingsizebox.value = this.value.length;"
onKeyDown="return ca(event);"></textarea>
<br>
<input type="text" name="listingsizebox" value="0" size="4" maxlength="3" readonly>
</form>
</body>
</html>
Thanks!
-Ollie
I know this is a somewhat common task, but I'm having problems with my implementation. I'm trying to write code that limits a textarea to a certain number of characters (in my case, 250). I want to do this interactively, where the user cannot type anything over 250 characters. I'm not too concerned about cut&paste at this point, though I might update the script later if it becomes a common issue.
Anyway, here's what I have for code. Any suggestions are appreciated! :)
<html>
<head>
<title>Test</title>
<script language="JavaScript" type="text/javascript">
// set up allowable characters
var reg = /(\x46|\x08|\x09)/; // backspace, delete & tab chars
// function to limit textarea to 250 characters
function ca(e) {
// set up variables
var key;
var area;
if (window.event) {
// IE
key = e.keyCode;
area = e.srcElement;
} else if (e.which) {
// netscape
key = e.which;
area = e.target;
} else {
// no event, so pass through
return true;
}
// if the length is under 250 or it's a delete, space, or tab, allow it
// otherwise, disallow
if (area.value.length < 250 || reg.test( String.fromCharCode(key)) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<form name="form1">
<textarea name="thearea"
rows="5"
cols="30"
onKeyUp="listingsizebox.value = this.value.length;"
onKeyDown="return ca(event);"></textarea>
<br>
<input type="text" name="listingsizebox" value="0" size="4" maxlength="3" readonly>
</form>
</body>
</html>
Thanks!
-Ollie