Limit chars in textarea: problem with copy-paste

I need to limit the chars typed in a textarea to 160 (size of an SMS :p) It works fine - as long as no one is copy-pasting text to it. Then my lil JS fails boohoo. So, could anyone help me out? Should I nail this to some other event than OnKeyPress or what?

Thanks in advance
[vbs]
function LimitText(fieldObj,maxChars)
{
var result = true;
if (fieldObj.value.length > maxChars)
{
result = false;
}

if (window.event)
{
window.event.returnValue = result;
}

return result;
}

Usage:
<textarea name=“myTextArea” OnKeyPress=“LimitText(this,160)”>
[/vbs]

-Z-

That would be quite easy if it was a text input box instead of a textarea, but I guess the problem with that would be that 160 chars is a lot longer than most input boxes, and so the user wouldn’t easily be able to check over their sms entirely before posting…

Hmmmm…

Well that didn’t help! :stuck_out_tongue:

Heh, its not about sending an SMS, the length just happens to be same :slight_smile: And it cannot be a textbox, it’d look stupid.

-Z-

No problem, just change your event. Instead of checking the length after each keystroke, check the total length after the text area loses focus:


<script language="javascript">
function LimitText(ref,iLength) {
  if(ref.value.length > iLength) {
	alert("Text length cannot be greater than " + iLength + " characters\
Current length is: " + ref.value.length);
	ref.focus();
  }
}
</script>

<textarea name="myTextArea" OnBlur="LimitText(this,160)">

Thanks mate, solves the problem :slight_smile:

What happens to javascript form validation when javascript is turned off?

Originally posted by Markdidj
What happens to javascript form validation when javascript is turned off?

It doesn’t work. Thats why its only safe to use if you know how your user will be accessing your site, like a corporate intranet or something. Otherwise, validation should be done server side.

<script type=“text/javascript”>
function LimitText(fieldObj,maxChars)
{
var result = true;
if (fieldObj.value.length > maxChars)
{
result = false;
}
if (window.event)
{
window.event.returnValue = result;
}
return result;
}
</script>
<textarea name=“myTextArea” OnKeyPress=“LimitText(this,4)”></textarea>

This is not working in the mozila firefox.It’s only working with Internet Expolrer.

Please give me solution for this quote

window.event only exists for Internet Explorer. All other browsers pass the event as a parameter in the call itself.