Tom Cole wrote on 26 apr 2007 in comp.lang.javascript
:
On Apr 26, 6:32 am, lamp <lam...@gmail.comwrote:
>Hello,
I want 1 Textarea which can take only 20 characters. It can't input
more
than 20 characters.
Please, guide me.
Thanks in advance
You can use the onkeyup event to capture each keypress and test for
length. If over 20 then truncate it to the first 20. Use onkeyup,
because onkeypress or onkeydown will append the character AFTER your
function has been called, resulting in 21 characters, where the 21st
character changes to the last typed character.
For example let's say we have a textarea with id="test":
function testLength() {
var value = document.getElementById('test').value;
if (value.length 20) {
document.getElementById('test').value = value.substring(0,
20);
}
}
No "if" needed!
===========================================
<script type='text/javascript'>
function testLength(v) {
v.value = v.value.substr(0,20);
}
</script>
<textarea onkeyup='testLength(this);'></textarea>
===========================================
>
<textarea id="test" onkeyup="testLength();"></textarea>
Now the test textarea will be limited to 20 characters. HTH.
But how would you know the letter typed in was the rightmost one?
Try this:
==========================
<script type='text/javascript'>
var textboxtextSave = '';
function testLength(test) {
if (test.value.length 20)
test.value = textboxtextSave
else
textboxtextSave = test.value;
};
</script>
<textarea onkeyup='testLength(this);'></textarea>
==========================
[This also will warrant some ctrl-V conciderations.]
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)