This is meant to allow a user to type in a message and then press enter to send it. This should clear the box so that the user can type in a new message. The problem is that the standard result of pressing enter (creation of a newline) is occurring after the .empty() event….so the text vanishes and is replaced by a newline, which is quite undesirable. How can I circumvent this?
$('#messagebox').keypress(function(event) {
if (event.keyCode == '13') {
send();
$('#messagebox').empty();
}
});
You can prevent the default action of the
keypressviaevent.preventDefault()(orreturn falsefrom your event handler function, which is jQuery shorthand forpreventDefault+stopPropagation):Live example | source:
HTML:
JavaScript:
FWIW, I’d probably use
valwith an empty string rather thanemptyto clear the textarea, sincevalis specifically for setting the value of form fields — but ifempty()is working for you…