473,769 Members | 1,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Limit <textarea> length without losing caret position

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,
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
Jun 27 '08 #1
7 3113
TRY...

<script type="text/javascript">
function cutLength(e,el, max)
{
if(el.value.len gth>max)
{
return false;
}else{
return true;
}
}
</script>
<form>
<input type="text" onkeypress="ret urn cutLength(event ,this,10)" /--
limit to 10 characters<br/>

<textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
limit to 100 characters<br/>
</form>
....How ever, this wont stop people cutting and pasting in over the
limit, it will only stop people when typing normally.

Graham
Jun 27 '08 #2
Laser Lips escribió:
<script type="text/javascript">
function cutLength(e,el, max)
{
if(el.value.len gth>max)
{
return false;
}else{
return true;
}
}
[...]
<textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
[...]
...How ever, this wont stop people cutting and pasting in over the
limit, it will only stop people when typing normally.
It's an idea but it needs quite polishing: in Firefox, once you hit the
limit you can't use the arrow keys or delete with keyboard. And the
clipboard issue would be a problem :( Anyway, thanks for the hint.

I can think of two approaches:

1. Listening to textarea events: if an event will result in value being
changed, then cancel the event.

2. Good old "if value too large then cut value" with caret position
handling: save position, cut text and restore position.

Both look like a lot of work.. *gasp*
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
Jun 27 '08 #3
On May 9, 8:57*am, "Álvaro G. Vicario"
<alvaroNOSPAMTH A...@demogracia .comwrote:
Laser Lips escribió:
<script type="text/javascript">
function cutLength(e,el, max)
{
* *if(el.value.le ngth>max)
* *{
* * * * * *return false;
* *}else{
* * * * * *return true;
* *}
}
[...]
<textarea onkeypress="ret urn cutLength(event ,this,100)"></textarea--
[...]
...How ever, this wont stop people cutting and pasting in over the
limit, it will only stop people when typing normally.

It's an idea but it needs quite polishing: in Firefox, once you hit the
limit you can't use the arrow keys or delete with keyboard. And the
clipboard issue would be a problem :( Anyway, thanks for the hint.

I can think of two approaches:

1. Listening to textarea events: if an event will result in value being
changed, then cancel the event.

2. Good old "if value too large then cut value" with caret position
handling: save position, cut text and restore position.

Both look like a lot of work.. *gasp*

--
--http://alvaro.es- Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:http://bits.demogracia.com
-- Mi web de humor al baño María:http://www.demogracia.com
--
This doesn't work?

<script type="text/javascript">
function getCaretPositio n (ctrl) {
var caretPos = 0;
if (document.selec tion) {
ctrl.focus ();
var Sel = document.select ion.createRange ();
Sel.moveStart ('character', -ctrl.value.leng th);
caretPos = Sel.text.length ;
}
else if (ctrl.selection Start || ctrl.selectionS tart == '0') {
caretPos = ctrl.selectionS tart;
}
return caretPos;
}
function setCaretPositio n(ctrl, pos) {
if(ctrl.setSele ctionRange) {
ctrl.focus();
ctrl.setSelecti onRange(pos,pos );
}
else if (ctrl.createTex tRange) {
var range = ctrl.createText Range();
range.collapse( true);
range.moveEnd(' character', pos);
range.moveStart ('character', pos);
range.select();
}
}

function checkMax(elemen t, max) {
var caretpos = getCaretPositio n(element);
var value = element.value;
if (value.length max) {
value = value.substring (0, max);
}
element.value = value;
setCaretPositio n(element, caretpos);
}
</script>
...
<textarea cols="5" rows="50" onkeyup="checkM ax(this, 25);"></textarea>

Jun 27 '08 #4
In comp.lang.javas cript message <7c50f285-c43f-4f29-9d36-b4bb5ae7a922@f3
6g2000hsa.googl egroups.com>, Fri, 9 May 2008 05:07:21, Laser Lips
<lo*********@gm ail.composted:

The advice of anyone who posts this code
>function cutLength(e,el, max)
{
if(el.value.len gth>max)
{
return false;
}else{
return true;
}
}
rather than

function cutLength(e, el, max) { return el.value.length <= max }

is unlikely to be worth considering.

--
(c) John Stockton, nr London UK. ??*@merlyn.demo n.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Jun 27 '08 #5
Tom Cole escribió:
This doesn't work?

<script type="text/javascript">
function getCaretPositio n (ctrl) {
var caretPos = 0;
[...]

It works badly in IE 6. However, it contains some good ideas. If I can't
find a prewritten script and I have to write mine, I'll take them into
account.
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
Jun 27 '08 #6
On May 13, 3:51 pm, "Álvaro G. Vicario"
<alvaroNOSPAMTH A...@demogracia .comwrote:
Tom Cole escribió:This doesn't work?
<script type="text/javascript">
function getCaretPositio n (ctrl) {
var caretPos = 0;

[...]

It works badly in IE 6. However, it contains some good ideas. If I can't
find a prewritten script and I have to write mine, I'll take them into
account.

--
--http://alvaro.es- Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:http://bits.demogracia.com
-- Mi web de humor al baño María:http://www.demogracia.com
--
<script>
function textLimit(field , maxlen)
{
if (field.value.le ngth maxlen)
{
field.value = field.value.sub string(0, maxlen); // if the length
is more than the limit (maxlen) then take only the first 'maxlen' no.
of characters
}
return (maxlen - field.value.len gth); // current value length is
returned back
}
</script>

<textarea onkeyup='textLi mit(this,100);r eturn false'></textarea>
Jun 27 '08 #7
pradeep wrote:
<script>
<script type="text/javascript">
function textLimit(field , maxlen)
{
if (field.value.le ngth maxlen)
{
field.value = field.value.sub string(0, maxlen); // if the length
is more than the limit (maxlen) then take only the first 'maxlen' no.
of characters
}
return (maxlen - field.value.len gth); // current value length is
returned back
}
</script>

<textarea onkeyup='textLi mit(this,100);r eturn false'></textarea>
| but all my Google searches either lead to obsolete scripts that
| overwrite the "value" property (thus losing caret position)
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #8

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

Similar topics

1
4725
by: Augustus | last post by:
Hiya, I have a form with a <textarea></textarea> to receive user input. This input is then stored in a database and sent by fax... I need to be able to remove the carriage returns (enter key... vbcrlf...) from the input so that somebody doesn't do something like fill the textarea with 100s of keypresses of the enter key and end up spitting out tonnes of blank pages on the fax machine
4
4327
by: Dennis Allen | last post by:
Hi. I hope someone here can help. I'm webmaster for a local astronomy club. Just went over our web site. Have validated every htm file on the site except: http://validator.w3.org/check?uri=http://www.stargazing.net/mas/COMET.htm In the <textarea> of this page I have Javascript code. I can't figure out how to present this code and still be w3c valid. Any advice would be appreciated...Dennis
5
12155
by: Jesper Rønn-Jensen | last post by:
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
3
7186
by: Bart Van der Donck | last post by:
Hello, I have a dynamic page of which I don't know how many forms will be on it, neither which and how many elements will be in each form. I use the following java script to disable all elements from all forms: var numberForms = document.forms.length; var formIndex;
11
13725
by: Les Paul | last post by:
I'm trying to design an HTML page that can edit itself. In essence, it's just like a Wiki page, but my own very simple version. It's a page full of plain old HTML content, and then at the bottom, there's an "Edit" link. So the page itself looks something like this: <HTML><HEAD><TITLE>blah</TITLE></HEAD><BODY> <!-- TEXT STARTS HERE --> <H1>Hello World!</H1> <P>More stuff here...</P>
3
6786
by: Jarek Mielcarek | last post by:
hi all, in xml file I have some fields which are source for <textarea> element. I'd like to transform this file using xslt and set the rows property of <textarea> depend of lines in some source field. How to do this? regards jaro
2
2469
by: Michael | last post by:
Question 1 ---------------- I am writing an advanced BBCode system for my forums and I would like to be able to find where the cursor was positioned last in the text so I could insert the BBCode there. Question 2 ---------------- Again I am writing an advanced BBCode system for my forums and I would like to make is so that when someone puts in a tag it goes bold, so
6
31451
by: Tony | last post by:
The w3schools HTML tag reference for <textarea> http://www.w3schools.com/tags/tag_textarea.asp says that the attributes 'cols' and 'rows' are REQUIRED attributes for the textarea tag. Looking at the HTML 4.01 specification I see this, too. What I'm wondering is - 'cols' & 'rows' determines the height & width of a textarea. So shouldn't that be something that is handled by CSS instead? What would be the practical consequence of leaving...
3
5671
by: FunkHouse9 | last post by:
I'm working on a form to collect data in a textarea which and am trying to keep returns and spaces. I have a couple of functions that I Frankensteined together to replace returns with <br> and to replace spaces with &nbsp;. The <br> part works well enough, but I keep getting "%20" instead of "&nbsp;" for the spaces. I understand that escape() changes " " to "%20", but I would think the ConvertSpaces function below would change the %20 to...
0
10211
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
10045
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...
1
9994
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
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
8870
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...
1
7408
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
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();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
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.