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.
Javascript Code for Line Break Removal someText = someText. replace(/(\r\n|\n|\r)/gm,""); The second piece of code with the javascript replace method removes all three types of line breaks by using this bit of a regular expression: \r\n|\n|\r.
To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.
Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.
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;
});
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("");
}
}
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With