473,778 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Limit textarea length

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.javas cript 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.setInter val 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.clearInt erval

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

Jul 23 '05 #1
5 12156
"Jesper Rønn-Jensen" <je******@gmail .com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
I have a textarea that must be limited to 70 characters. No big deal --
at least so I thought.


[snip]

Why not just use a "text" field?

<input type="text" name="data" size="70" maxlength="70">

You can also set "size=" to somerthing else if it doesn't fit on your page.


Jul 23 '05 #2
Thanks for your quick reply.
Why not just use a "text" field?


Text field is a no-go because I cannot input line breaks. Sorry, that
would have been easy. I must use a textarea.

Jul 23 '05 #3
Jesper Rønn-Jensen wrote:
Thanks for your quick reply.
Why not just use a "text" field?

Text field is a no-go because I cannot input line breaks. Sorry, that
would have been easy. I must use a textarea.


Most people would not include line breaks in their character
count (if they actually try to count the characters at all).

Why not have your event listener write the current number of
characters to a place in the page next to the text area. When
it exceeds 70 characters, make it red and bold. If the user
submits the form with too many characters, give them an error
message and send them back to fix it.

Attempting to automate character removal will likely just bind
you in ever more complex "what if..." scenarios. And randomly
removing characters from the end of the supplied text to make it
only 70 characters will likely frustrate users - what if the bit
you programmaticall y trimmed was something they wanted kept, and
some other part trimmed?

The only way they'll know they've hit the magic number is if
they notice characters disappearing from the end of the text.

It's like when you type an incorrect URL into the browser
address bar. Having advised you of the error, the browser
should leave the incorrect text there and let you fix it,
rather than display the URL of the error page (as some browsers
still do).

Users aren't dumb. Give them appropriate information and a
helpful (not interventionist ) interface and they'll respond much
better.

--
Rob
Jul 23 '05 #4
Jesper Rønn-Jensen <je******@gmail .com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.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.javas cript 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.setInter val 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.clearInt erval

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>Past e text above into text area below.</B><BR><BR>
<script>
function chopText(elem, limit)
{
if(elem.value.l ength>limit)
elem.value=elem .value.substrin g(0,limit);

document.f1.cLe ft.value=limit-elem.value.leng th
}

setInterval("ch opText(document .f1.ta1,70)",10 00);

</script>

<form name="f1">
<BR>
<textarea name='ta1' rows=5 cols=40 onchange=onkeyu p="chopText(thi s,70)"</TEXTAREA>

<BR>Character s Remaining
<input size=3 type="text" name="cLeft">
</form>
</body>
</html>

--
S.C.
http://makeashorterlink.com/?H3E82245A

Jul 23 '05 #5
Stephen Chalmers wrote:
[...]
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:
A good start, so here's an similar version that implements a
less interventionist approach (i.e. it warns, not does). I
shortened the interval too - 1 second was a tad long for me.
<html><head><ti tle>Character play</title></head>
<body>
<BR>"If you are going through hell, the best thing to do
is to keep going" - Winston Churchill
<BR><BR><B>Past e text above into text area below.</B><BR><BR>
<script type="text/javascript">
function checkText(elem, limit) {
var charRemaining = limit - elem.value.leng th;

if (document.getEl ementById) {
var aText = document.getEle mentById('alert Text');
var aNumber = document.getEle mentById('alert Number');
} else if (document.all) {
var aText = document.all['alertText'];
var aNumber = document.all['alertNumber'];
}

if (aText && aNumber) {
if (charRemaining < 0) {
aText.innerHTML = '<b>Too many characters, remove:&nbsp;';
aNumber.innerHT ML = '<b>' + Math.abs(charRe maining)
+ '</b>';
} else {
aText.innerHTML = 'Characters remaining:&nbsp ;'
aNumber.innerHT ML = charRemaining;
}
}
}

setInterval("ch eckText(documen t.f1.ta1,70)",5 00);

</script>

<form name="f1" action="">
<BR>
<textarea name='ta1' rows="5" cols="40"
onchange=onkeyu p="checkText(th is,70)"</TEXTAREA>


<BR><span id="alertText"> Characters Remaining:</span>
<span id="alertNumber " style="
border: 1px solid red;
padding: 4 4 4 4;">70</span>
</form>
</body>
</html>
--
Rob
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
23081
by: Jay | last post by:
I have an HTML form with a textarea. When passing large amount of data in the textarea, the Processing asp pages catch an error message as follows: Error Type: (0x80020009) Exception occurred. The error is generated once the trim or length or replace function is called on the field when long text is passed in the textarea.
4
29535
by: wing | last post by:
Hi all, I find a JavaScript that limits the field length in a textarea, but it is not completed. The script does not handle the copy and paste case. For example, says the textarea field length is limited to 5 and a 6-character length text is pasted, no event is triggered. (The script only handles onKeyPress and onKeyUp)
1
3576
by: Volt | last post by:
is there any way to select and mark part of text in textarea by regular expression? i need to select the first string in textarea whitch is like xxxxx,xxx where x is any character
10
1641
by: M K | last post by:
Is there a way to limit an asp:textarea to 100 chars on the client side? The db only accepts 100 and chops the rest off.
5
2224
by: JohnSouth | last post by:
Hi In a TextBox I can set a maximum size for the entry. Is there a way of limiting the number of characters being entered into a TextArea control? John South www.wherecanwego.com
6
3488
by: @sh | last post by:
Guys, Working on a function to alert the user to too many characters being entered into a text area, I've put together this function so far borrowing bits from resource websites... function Ash_LimitMaxTextAreaCharacters(TheMaxCharacters,TheFriendlyFormName) { if(document.myform.box.value.length > TheMaxCharacters) { alert('Sorry but '+TheFriendlyFormName+' contains too many characters,
7
2152
Haitashi
by: Haitashi | last post by:
This is in the head: <script language="javascript" type="text/javascript"> function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } </script>
3
4205
by: teser3 | last post by:
I have the below that limits the textarea input to 500 characters but cant get the alert message to work. It doesnt show anything. Please advise. <script language="javascript" type="text/javascript"> function limitText(limitField, limitCount, limitNum) { if (limitField.value.length limitNum) { limitField.value = limitField.value.substring(0, limitNum); alert("You are trying to enter more than 500 characters"); } else {
7
3114
by: =?ISO-8859-1?Q?=22=C1lvaro_G=2E_Vicario=22?= | last post by:
I need to emulate the missing "maxlegth" attribute in "textarea" fields but all my Google searches either lead to obsolete scripts that overwrite the "value" property (thus losing caret position) or to complex solutions that work on top of specific frameworks. Do you have some reference on how to do it? I'd like to make it work in at least Firefox and IE 6 and 7. Thank you in advance,
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10292
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6722
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.