I have the following code, and I\'m kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left.
If you change your js to look like this it should work for you:
var $txtLenLeft = $('#txt-length-left'); // lets cache this since it isn't changing
$('#send-txt').keydown(function(e) { //take the event argument
var Length = $(this).val().length; // lets use 'this' instead of looking up the element in the DOM
var AmountLeft = maxLen - Length;
$txtLenLeft.html(AmountLeft);
if(Length >= maxLen && e.keyCode != 8){ // allow backspace
e.preventDefault(); // cancel the default action of the event
}
});
You can see a working example here: http://jsfiddle.net/aP5sK/2/
try this.
var charLmt = "200";//max charterer
$("#send-txt").keydown(function(){
var _msgLenght = $(this).val().length;
if (_msgLenght > charLmt) {
$(this).val($(this).val().substring(0, charLmt));
}
});
Got it with this:
$("#div_id").prop('maxlength', '80');
I really dont know if there's something wrong with this solution, but it worked for me.
Here's a solution using HTML5 data attribute to automatically bind to all needed textareas:
$('textarea[data-max-length]').live('keypress', function(e) {
if (String.fromCharCode(e.charCode || e.keyCode).match(/\S/) && $(this).val().length >= $(this).attr('data-max-length')) {
e.preventDefault();
}
});
Relying on keypress, keydown, keyup is a flawed solution because a user can copy and paste data into the textarea without pressing any keys.
To limit the length of text in a textarea with javascript regardless of how the data gets in there you must rely on a setInterval timer instead.
setInterval(function() {
if ($('#message').val().length > 250) {
$('#message').val($('#message').val().substring(0, 250));
}}, 500);
Obviously, I'm assuming you have an id of message assigned to your textarea.
Here it goes. Anything beyond character limit will be removed.
$('textarea').keypress(function(e) {
var tval = $('textarea').val(),
tlength = tval.length,
set = 10,
remain = parseInt(set - tlength);
$('p').text(remain);
if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
$('textarea').val((tval).substring(0, tlength - 1));
return false;
}
})