I have the following function to get the value in a textarea with the id #posttext and to call a function to post something.
I do not want the user to be able to type in more than one line break in a row. How can I prevent that?
Here’s the code:
//Post something
$('#postDiv').on('keydown', '#posttext', function(e) {
if (e.which==13 && !e.shiftKey && $('#posttext').val()!=' Post something...') {
//This is what I tried to prevent a user from inserting more than one br in a row
var last = false;
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
if (last) { e.preventDefault(); }
last=true;
}else{
last=false;
}
//If not currently loading and enough text typed in, submit
if($('#imageFeedback').html()!=' | Loading...' && $('#posttext').val().length>15){
//Say that it is loading
$('#imageFeedback').css('color','black').css('font-weight','normal').html(' | Loading...');
//Call function to post
post($(this));
return false;
}
}
});
It would be much better if you simply removed duplicate linebreaks later, e.g. with this regex:
s/\n{2,}/\n/gHowever, to do what you want, simply remove duplicate newlines onkeyup
Demo: http://jsfiddle.net/ThiefMaster/WJmhF/