Laser Lips escribió:
<script type="text/javascript">
function cutLength(e,el,max)
{
if(el.value.length>max)
{
return false;
}else{
return true;
}
} [...]
<textarea onkeypress="return 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 getCaretPosition (ctrl) {
var caretPos = 0;
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
caretPos = Sel.text.length;
}
else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
caretPos = ctrl.selectionStart;
}
return caretPos;
}
function setCaretPosition(ctrl, pos) {
if(ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
function checkMax(element, max) {
var caretpos = getCaretPosition(element);
var value = element.value;
if (value.length > max) {
value = value.substring(0, max);
}
element.value = value;
setCaretPosition(element, caretpos);
}
</script>
...
<textarea cols="5" rows="50" onkeyup="checkMax(this, 25);"></textarea>