Remove line break from textarea
Solution 1
The problem is that the Enter keypress is not being suppressed and is doing its usual browser behaviour (i.e. adding a line break). Add return false
to the end of your keypress handler to prevent this.
$("#area").keypress(function (e) {
if (e.keyCode != 13) return;
var msg = $("#area").val().replace(/\n/g, "");
if (!util.isBlank(msg))
{
send(msg);
$("#area").val("");
}
return false;
});
Solution 2
Thomas, the e.preventDefault(); would need to be wrapped inside a conditional applying it only to the enter key.
// Restrict ENTER.
if (e.keyCode == '13') { e.preventDefault(); }
The whole function would look something like this (with commenting):
// Key Press Listener Attachment for #area.
$("#area").keypress( function (event) {
// If the key code is not associated with the ENTER key...
if (event.keyCode != 13) {
// ...exit the function.
return false;
} else {
// Otherwise prevent the default event.
event.preventDefault();
// Get the message value, stripping any newline characters.
var msg = $("#area").val().replace("\n", "");
// If the message is not blank now...
if (!util.isBlank(msg)) {
// ...send the message.
send(msg);
// Clear the text area.
$("#area").val("");
}
}
} );
user478419
Updated on July 09, 2022Comments
-
user478419 almost 2 years
I have a textarea like this:
<textarea tabindex="1" maxlength='2000' id="area"></textarea>
I watch this textarea with jquery:
$("#area").keypress(function (e) { if (e.keyCode != 13) return; var msg = $("#area").val().replace("\n", ""); if (!util.isBlank(msg)) { send(msg); $("#area").val(""); } });
send() submits the message to the server if the return key was pressed and if the message is not blank or only containing line spaces.
The problem: After sending the message, the textarea is not cleared. On the first page load, the textarea is empty. Once a message was submitted, there is one blank line in the textarea and I don't know how to get rid of it.
-
user478419 over 13 yearsThat doesn't work. As you can imagine, the textarea is meant for text input. If I prevent the default action, then I am not able to enter anything.
-
Orlando over 10 yearsreplace should be
replace(/\n/g, "");
replace("\n", "") will only delete the first new line -
Tim Down over 10 years@Orlando: That line of code came straight from the question so it's possible that's replacing just the first line break is what the OP intended, but I agree it's unlikely.
-
Admin almost 8 yearsTo be consistent with all the line breaks,
/(\r?\n|\r\n?)/
is best. -
Tim Down almost 8 years@AnirudhBalaji: jQuery's
val()
method normalizes line breaks to\n
. -
SourceVisor almost 7 yearsJust for a bit of elegance, I would think that you'd simply check
if (event.keyCode == 13) { // do something; }
and save yourself the extra 3-lines where you return false if keyCode is not equal to 13.