How can I prevent the user from inserting more than one line break in a row into a text field?
I prefer a solution using jQuery.
UPDATE 1:
I have inserted anadeo’s code into my code which looks like the following. Unfortunately it doesn’t work – it still allows more than one line break in a row in the textarea #posttext. Anyone know how to fix this? Thanks 🙂
//Post something
$('#postDiv').on('keydown', '#posttext', function(e) {
if (e.which==13 && !e.shiftKey && $('#posttext').val()!=' Post something...') {
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;
}
}
});
FIDDLE
Are you thinking of avoiding more than one line break in a row (one after another), like so:
FIDDLE
EDIT:
Firstly,
on()is only supported in jQuery 1.7+, so make sure you are using a newer version of the library.You are also using the delegated version of
on(), and that should’nt be a problem, but it assumes that your textarea is inserted into the DOM at a later time, and not present from the start, ie. it’s dynamically inserted with JS etc.The rest seems ok, but the
lastvariable will have to be placed outside the keydown function to work properly, and the varcodeshould be at the top, doing the check for the enter key only once, as the second check is not really necessary.The
codevariable is really optional, as jQuery is supposed to normalizee.which, but doing a check to see ifkeycodeorwhichis supported seems like a good idea to ensure cross browser compatibility.The check for the
#posttextvalue will only work once, as soon as a linebreak is entered the value is no longerPost something..., and the “limit linebreaks” function will be enabled?All in all I think this should work, try it and see ?
FIDDLE
Also, It would probably be a good idea to use a less common variable name instead of
last, something likeMyLastTyped,PostTextLastetc. that is less likely to be confused with a function or variable with the namelastin some other place or plugin etc.