How do I "lock" a textarea with jQuery so that no more characters can be entered? I don't want to necessarily disable it since I want to allow characters to be deleted.
update: oops..it just came to me: if I am limiting the length to say 400 characters then i can use the following when the length is > 400:
this.value = this.value.substring(0, 400);
which will just trim the excess
following is quick contraption from modification of jquery.numeric plugin :)
It allows special keys but don't let user type anything.
<textarea id="txt" rows="5" cols="50"></textarea>
<script type="text/javascript">
$(document).ready(function(){
$("#txt").keypress(function(e){
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
// allow Ctrl+A
if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65)
/* opera */) return true;
// allow Ctrl+X (cut)
if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88)
/* opera */) return true;
// allow Ctrl+C (copy)
if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67)
/* opera */) return true;
// allow Ctrl+Z (undo)
if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90)
/* opera */) return true;
// allow or deny Ctrl+V (paste), Shift+Ins
if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86)
/* opera */
|| (e.shiftKey && key == 45)) return true;
//page up, down, home end, left-right-up-down
if(key > 32 && key < 40) return true;
// if DEL or BACKSPACE is pressed
return key == 46 || key == 8;
});
});
</script>
Try this:
$("textarea").keypress(function(){
if($(this).val().length>=10)
return false;
});
Demo here: http://jsbin.com/erama
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With