[jQuery] Limit lines and characters of textarea
This is what I'm trying to do with a textarea.
1. Limit number of characters
2. Limit number of lines
3. Diminish linelimit if characters in line exceed charlimit/linelimit
4. Substract number of "lost" chararacters from charlimit if linebreak
("\n") is provoked
5. Disable input when either limit is reached
So far I have managed to get 1, 2 and 5 (buggy) to work with the
following function. A demo can tested at http://sidisinsane.com/sandbox/jquery/limitentry/
function limitEntry(txtid,infid,linelimit,charlimit)
{
var txt = $('#'+txtid).val();
var txtlength = txt.length;
var line = txt.replace(/\s+$/g,"");
var split = line.split("\n");
var splitlength = split.length;
if(splitlength > linelimit || txtlength > charlimit)
{
$('#'+infid).html('Your entry has reached its limit!');
$('#'+txtid).val(txt.substr(0,linelimit));
$('#'+txtid).val(txt.substr(0,charlimit));
return false;
}else{
$('#'+infid).html((linelimit - splitlength)+' lines and '+
(charlimit - txtlength)+' characters left.');
return true;
}
}
$(document).ready(function()
{
$(function()
{
$('#entry').keyup(function()
{
limitEntry('entry','counter',5,100);
})
});
});
I've tried a couple of things but didn't quite manage to achieve my
goals. I could use some help on this one.