Jesper Rønn-Jensen <> wrote in message
news: oups.com...
> I have a textarea that must be limited to 70 characters. No big deal --
> at least so I thought.
> * Textarea must not exceed 70 characters
> * Exceeding content must be cut off
> * Must work on input by keyboard (keypress, keyup events)
> * Must work on pasted input from context menu
> * Must work on pasted input via CTRL+V and similar
> * Must work on pasted input via browsers menu>Edit>Paste
> * Must work in Mozilla + IE and coded via W3C standards
>
> I found quite some discussions here in comp.lang.javascript on this
> subject, but all lack the discussion of non-keyboard inputs.
>
> So far, I concluded to avoid using the onkeyup or onkeypress events -
> they do not capture when data pasted via the mouse.
>
> This is what I do now, but there are still problems.
> * Textarea onfocus() adds a window.setInterval eventlistener to check
> the textarea value 10 times per second.
> * If textarea.value exceeds 70 characters, set textarea.value to
> substring(0,69)
> * Textarea onblur() removes eventlistener via window.clearInterval
>
> This works when I paste text in all ways and when I enter data by
> keyboard from one end to the other. BUT as soon as I add text at the
> beginning of the textarea, then the end text is cut off and cursor is
> moved to the end of textarea.
>
> My idea would work OK if I could figure out a way to move cursor back
> to its position when I finish cropping textarea text. As you might see,
> I'm a bit stuck here.
> Any suggestions appreciated,
>
> Thanks in advance,
>
> Jesper
>
Keyboard events are no problem, but I know of no event-driven way of
limiting pasted text other than with onchange, which doesn't fire until the
textarea loses focus. Of course you can use setInterval() to monitor the
length of the text periodically and limit it if necessary. Aside from
user-friendliness issues already mentioned, you could see if this meets your
needs:
<html>
<body>
<BR>My dear Watson," said he, "I cannot agree with those who rank modesty
among the virtues. To the logician all things must be seen exactly as they
are, and to underestimate oneself is as much a departure from truth as to
exaggerate one's own powers."
<BR><BR><B>Paste text above into text area below.</B><BR><BR>
<script>
function chopText(elem, limit)
{
if(elem.value.length>limit)
elem.value=elem.value.substring(0,limit);
document.f1.cLeft.value=limit-elem.value.length
}
setInterval("chopText(document.f1.ta1,70)",1000);
</script>
<form name="f1">
<BR>
<textarea name='ta1' rows=5 cols=40 onchange=onkeyup="chopText(this,70)"
></TEXTAREA>
<BR>Characters Remaining
<input size=3 type="text" name="cLeft">
</form>
</body>
</html>
--
S.C.
http://makeashorterlink.com/?H3E82245A