JQuery .append line break in text area on hitting return
I need to be able to go to the next line after hitting the 'Enter' (keycode == 13) after entering some text. This works if you hit 'Enter' before you enter any text but not after. Here's some of my script
var keyPressedOnContactUsMessageHandler = function (e) {
if (e.which == 13 || e.keyCode == 13) {
$(this).append(" \n\n");
if ($("#ContactUsMessage").focus()) {
开发者_开发技巧 return false;
} else {
return true;
}
sendMessage();
blockEnterKeyHandler(e);
}
};
I think the problem is probably that you have a textarea
and are attempting to add content to it with append
. The HTML content of a textarea
element is only relevant when the page is parsed. After that, the text contained is referred to by the value
property. You should modify this instead.
this.value += '\n\n';
My guess is that your browser is being generous: if you modify the HTML before the value
is altered, it modifies the value
accordingly. It's better just to modify the value
yourself.
Also, $("#ContactUsMessage").focus()
will always return a truthy value. If you are trying to test whether the element is focused, use is
:
if ($('#ContactUsMessage').is(':focus')) {
NB that this does not work in older browsers if you are using a version of jQuery before 1.6.
Also, after you fix that, this section
sendMessage();
blockEnterKeyHandler(e);
never gets reached because you always return something before it with this if statement
if($("#ContactUsMessage").focus()) {
return false;
} else {
return true;
}
精彩评论